R 网络数据


许多网站为其用户提供消费数据。例如,世界卫生组织 (WHO) 以 CSV、txt 和 XML 文件的形式提供健康和医疗信息报告。使用 R 程序,我们可以以编程方式从此类网站中提取特定数据。 R 中一些用于从 web 中抓取数据的包是:“RCurl”、XML”和“stringr”。它们用于连接到 URL,识别文件所需的链接并将它们下载到本地环境。

安装 R 包


处理 URL 和文件链接需要以下软件包。如果它们在你的 R 环境中不可用,你可以使用以下命令安装它们。

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

输入数据


我们将访问网址 天气数据 并使用 R 下载 2015 年的 CSV 文件。

例子


我们将使用函数 获取HTMLLinks() 收集文件的 URL。然后我们将使用函数 下载文件() 将文件保存到本地系统。由于我们将一次又一次地为多个文件应用相同的代码,因此我们将创建一个要多次调用的函数。文件名作为参数以 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"