许多网站提供供其用户使用的数据.例如,世界卫生组织(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()将文件保存到本地系统.因为我们将再次应用相同的代码a再次为多个文件,我们将创建一个多次调用的函数.文件名作为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"