R 循环:在 url 中下载多个具有不同日期的 csv 文件

R loop: Downloading multiple csv files with varying dates in the url

我想从以下网站下载一个月中所有天的天气数据:

https://www.wunderground.com/history/airport/KSEA/2013/1/8/DailyHistory.html?format=1

我意识到这可以通过更改上述网站中的日期来完成link。例如,对于 1 月 9 日,link 将是

...KSEA/2013/1/9/DailyHistory.html?format=1

因此,当我单独下载这些数据时,我能够获取 csv 文件,但是当我尝试为整个月编写一个 for 循环时,它就是不起作用。以下是我用于单个文件下载的代码:

download.file(url = 'https://www.wunderground.com/history/airport/KSEA/2013/1/8/DailyHistory.html?MR=1&format=1',
              destfile = "/Users/ABCD/Desktop/weather.csv") 

如有任何帮助,我们将不胜感激。

您可能会感到惊讶,在 url 中使用“2013/01/08”而不是“2013/1/8”也可以。这使事情变得更容易,因为我们可以在 R.

中使用 "Date" 对象

以下函数将下载从开始日期(例如“2013/01/01”)到结束日期(例如“2013/02/28”)的所有数据。您可以自定义开始日期和结束日期。最后,下载的文件将是,例如,“/Users/ABCD/Desktop/weather/2013-01-01.csv”。 (您需要先建立目录"/Users/ABCD/Desktop/weather")。

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("/Users/ABCD/Desktop/weather/", string_date, ".csv")
    string_date <- gsub("-", "/", string_date)  ## replace "-" with "/"
    myurl <- paste("https://www.wunderground.com/history/airport/KSEA", string_date, "DailyHistory.html?MR=1&format=1", sep = "/")
    download.file(url = myurl, destfile = myfile, quiet = TRUE)
    }
  }

mydownload("2013/01/01", "2013/02/28")

评论:

  1. 最初我用

    for (mydate in dates) {
      string_date <- as.character(mydate)
    

    但答案不对。 mydate 以某种方式被强制转换为整数。最后我要做的

    for (i in 1:length(dates)) {
      string_date <- as.character(dates[i])
    
  2. 在这里使用 for 循环比较合适。无需执行 lapply 或类似操作,因为 download.file() 需要相当长的时间,因此循环开销微不足道。