r - 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)
解决方案
我很惊讶以前没有人回答过这个问题。嗯,我喜欢这样的东西,所以我试了一下。这就是我想出的。更改脚本以满足您的需要(即 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")
推荐阅读
- java - Cmis 方法 getAllVersions 的异常:CmisNotSupportedException:此对象的存储库不支持操作
- node.js - 如何将heroku服务器连接到mongodb?
- php - 如何为一个 ID 存储多个项目?
- javascript - 为什么我的函数只能使用一个 ID?
- model - 在 Sequelize 中使用模型和迁移
- javascript - 如何强制页面始终滚动到底部?
- arrays - 获取无错误范围内的数组元素
- sharepoint - 如何在 Sharepoint CSOM 代码以下加速?
- javascript - 如何发送 res.render 字符串参数并将其呈现为 HTML?
- angular - 突出显示搜索结果时处理大写