R教程

R 网络数据

许多网站都提供供其用户使用的数据。例如,世界卫生组织 (WHO) 以 CSV、txt 和 XML 文件的形式提供有关健康和医疗信息的报告。使用 R 程序,我们可以以编程方式从此类网站中提取特定数据。 R 中的一些用于从网络上抓取数据的包是-"RCurl"、XML"和"stringr"。它们用于连接到 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"
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4