R-web-data

提供:Dev Guides
移動先:案内検索

R-Webデータ

多くのWebサイトは、ユーザーが使用するデータを提供しています。 たとえば、世界保健機関(WHO)は、CSV、txt、およびXMLファイルの形式で健康および医療情報に関するレポートを提供しています。 Rプログラムを使用すると、このようなWebサイトから特定のデータをプログラムで抽出できます。 Webからデータをスクラップするために使用されるRのパッケージには、「RCurl」、「XML」、および「stringr」があります。 URLに接続し、ファイルに必要なリンクを特定して、ローカル環境にダウンロードするために使用されます。

Rパッケージをインストールする

URLとファイルへのリンクを処理するには、次のパッケージが必要です。 R環境で使用できない場合は、次のコマンドを使用してインストールできます。

install.packages("RCurl")
install.packages("XML")
install.packages("stringr")
install.packages("plyr")

入力データ

URL 天気データにアクセスし、2015年のRを使用してCSVファイルをダウンロードします。

関数* getHTMLLinks()を使用して、ファイルのURLを収集します。 次に、関数 download.file()*を使用して、ファイルをローカルシステムに保存します。 同じコードを複数のファイルに何度も適用するため、複数回呼び出される関数を作成します。 ファイル名は、Rリストオブジェクトの形式でパラメーターとしてこの関数に渡されます。

# Read the URL.
url <- "http://www.geos.ed.ac.uk/~weather/jcmb_ws/"

# Gather the html links present in the webpage.
links <- getHTMLLinks(url)

# Identify only the links which point to the JCMB 2015 files.
filenames <- links[str_detect(links, "JCMB_2015")]

# Store the file names as a list.
filenames_list <- as.list(filenames)

# Create a function to download the files by passing the URL and filename list.
downloadcsv <- function (mainurl,filename) {
   filedetails <- str_c(mainurl,filename)
   download.file(filedetails,filename)
}

# Now apply the l_ply function and save the files into the current R working directory.
l_ply(filenames,downloadcsv,mainurl = "http://www.geos.ed.ac.uk/~weather/jcmb_ws/")

ファイルのダウンロードを確認する

上記のコードを実行すると、現在のR作業ディレクトリで次のファイルを見つけることができます。

"JCMB_2015.csv" "JCMB_2015_Apr.csv" "JCMB_2015_Feb.csv" "JCMB_2015_Jan.csv"
   "JCMB_2015_Mar.csv"