首页 > 解决方案 > R:从在线源导入多个文件

问题描述

我有 5 年的日常天气文件,称为“CUSTOM- ARC- date - METRIC.csv”,在这里 ( https://sci.ncas.ac.uk/leedsweather/Archive/ )。有没有办法将它们全部导入 R 中的一个大文件中?

我正在尝试此代码(基于此解决方案),但我收到一条错误消息,指出内容不是 XML。有什么想法吗?另外我只对-METRIC文件感兴趣。

url <- "https://sci.ncas.ac.uk/leedsweather/Archive/"
## query the url to get all the file names ending in '.csv'
weatherFiles <- XML::getHTMLLinks(
  url, 
  xpQuery = "//a/@href['.csv'=substring(., string-length(.) - 3)]"
)
## create a new directory 'weather' to hold the downloads
dir.create("weather")
## save the current directory path for later
wd <- getwd()
## change working directory for the download
setwd("weather")
## create all the new files
file.create(weatherFiles)
## download them all
lapply(paste0(url, weatherFiles), function(x) download.file(x, basename(x)))
## reset working directory to original
setwd(wd)

标签: rxmllapply

解决方案


我很惊讶以前没有人回答过这个问题。嗯,我喜欢这样的东西,所以我试了一下。这就是我想出的。更改脚本以满足您的需要(即 start_date 和 end_date...我刚刚输入了一个非常小的日期范围来测试功能)。

mydownload <- function (start_date, end_date) {
  start_date <- as.Date(start_date)  ## convert to Date object
  end_date <- as.Date(end_date)  ## convert to Date object
  dates <- as.Date("1970/01/01") + (start_date : end_date)  ## date sequence
  ## a loop to download data
  for (i in 1:length(dates)) {
    string_date <- as.character(dates[i])
    myfile <- paste0("C:/Users/Excel/Desktop/weather/", string_date, ".csv")
    string_date <- gsub("-", "-", string_date)  ## replace "-" with "/"
    myurl <- paste("https://sci.ncas.ac.uk/leedsweather/Archive/CUSTOM-ARC-", string_date, "-METRIC.csv", sep = "")
    download.file(url = myurl, destfile = myfile, quiet = TRUE)
    }
  }

mydownload("2013/11/25", "2013/11/30")

推荐阅读