位置:首頁 > 大數據教學 > R語言教學 > R語言處理Web數據

R語言處理Web數據

許多網站提供的數據,以供其用戶的消費。例如,世界衛生組織(WHO)提供的CSV,TXT和XML文件的形式的健康和醫療信息報告。基於R程序,我們可以通過編程提取這些網站的具體數據。R中一些程序包,用來提取網絡數據形式- "RCurl",XML", 和"stringr". 它們被用於連接到的URL,確定所需鏈接的文件,並將它們下載到本地環境。

安裝R程序包

下麵的軟件包都需要處理的URL和鏈接文件。如果它們冇有R環境中,可以使用下麵的命令進行安裝。

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

輸入數據

我們將訪問URL:氣象資料,並下載使用R中的CSV文件(這是在2015年之前的數據)。

示例

我們將使用函數getHTMLLinks()來收集文件的網址。然後,我們將使用函數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"