download.file関数を使う。第一引数にダウンロードしたいインターネット上のファイルをURLで、第二引数に保存するファイル名を指定する。以下は、2025年4月に、プロジェクト・グーテンベルクに掲載されている「赤毛のアン」の原著をテキストで納めているテキストファイルをダウンロードして、一時的なファイル名で保存した例。
当該ファイルは文字コードはUTF-8(BOM付き)、改行コードはCR+LFで保存されており、download.file関数のmodeオプションに"wb"を指定しないと、ダウンロード時に改行コードをCR+CR+LFに変換して保存するので注意(it does distinguish between text and binary files and for text transfers changes ‘\n’ line endings to ‘\r\n’ (aka ‘CRLF’).)。
> urlname <- "https://www.gutenberg.org/ebooks/45.txt.utf-8"
> filepath <- tempfile()
> download.file(urlname, filepath, mode = "wb")
URL 'https://www.gutenberg.org/ebooks/45.txt.utf-8' を試しています
Content type 'text/plain; charset=utf-8' length 606739 bytes (592 KB)
downloaded 592 KB
ダウンロードしたファイルを試しに読み込んでみる。最後に、ダウンローしたファイルは削除している。
> library(tidyverse)
> options(readr.show_progress = FALSE, readr.show_col_types = FALSE)
> lines <- read_lines(filepath, locale = locale(encoding = "UTF-8"))
> head(lines, 15)
[1] "The Project Gutenberg eBook of Anne of Green Gables"
[2] " "
[3] "This ebook is for the use of anyone anywhere in the United States and"
[4] "most other parts of the world at no cost and with almost no restrictions"
[5] "whatsoever. You may copy it, give it away or re-use it under the terms"
[6] "of the Project Gutenberg License included with this ebook or online"
[7] "at www.gutenberg.org. If you are not located in the United States,"
[8] "you will have to check the laws of the country where you are located"
[9] "before using this eBook."
[10] ""
[11] "Title: Anne of Green Gables"
[12] ""
[13] "Author: L. M. Montgomery"
[14] ""
[15] "Release date: June 27, 2008 [eBook #45]"
> tail(lines, 5)
[1] "including how to make donations to the Project Gutenberg Literary"
[2] "Archive Foundation, how to help produce our new eBooks, and how to"
[3] "subscribe to our email newsletter to hear about new eBooks."
[4] ""
[5] ""
> file.remove(filepath)
[1] TRUE