R 语言 Web 数据

  • 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")
    
  • 输入数据

    我们将访问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"