R語言Web數據

許多網站為用戶提供一些公開的數據。 例如,世界衛生組織(WHO)以CSV,txt和XML檔的形式提供關於健康和醫療資訊的報告。 使用R程式,我們可以從這些網站以編程方式提取特定的數據。 用於從網路中廢棄數據的R中的一些包是 - RCurlXMLstringr,用於連接URL,識別檔所需的鏈接並將其下載到本地環境。

安裝R包

需要以下包才能處理URL和鏈接到檔。 如果它們在R環境中不可用,則可以使用以下命令安裝它們。

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

準備輸入數據

我們將訪問URL天氣數據,並使用R來下載2015年天氣的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"

上一篇: R語言JSON檔 下一篇: R語言基礎語法