我想使用下面的代码执行循环来捕获来自多个站点的天气数据:
library(rwunderground)
sample_df <- data.frame(airportid = c("K6A2",
"KAPA",
"KASD",
"KATL",
"KBKF",
"KBKF",
"KCCO",
"KDEN",
"KFFC",
"KFRG"),
stringsAsFactors = FALSE)
history_range(set_location(airport_code =sample_df$airportid), date_start = "20170815", date_end = "20170822",
limit = 10, no_api = FALSE, use_metric = FALSE, key = get_api_key(),
raw = FALSE, message = TRUE)恐怕行不通。
发布于 2017-09-15 02:35:25
目前,您正在将整个向量(多个字符值)传递给history_range调用。只需通过lapply迭代传递向量值,甚至返回一组history_range()返回对象。下面使用已定义的函数来传递参数。根据需要扩展函数以执行其他操作。
capture_weather_data <- function(airport_id) {
data <- history_range(set_location(airport_code=airport_id),
date_start = "20170815", date_end = "20170822",
limit = 10, no_api = FALSE, use_metric = FALSE, key = get_api_key(),
raw = FALSE, message = TRUE)
write.csv(data, paste0("/path/to/output/", airport_id, ".csv"))
return(data)
}
data_list <- lapply(sample_df$airportid, capture_weather_data)此外,将列表中的每个项目命名为相应的airport_id字符值:
data_list <- setNames(data_list, sample_df$airportid)
data_list$K6A2 # 1st ITEM
data_list$KAPA # 2nd ITEM
data_list$KASD # 3rd ITEM
...实际上,使用sapply (lapply的包装器),您可以在同一调用中生成列表和命名每个项目,但输入向量必须是字符类型(而不是因子):
data_list <- sapply(as.character(sample_df$airportid), capture_weather_data,
simplify=FALSE, USE.NAMES=TRUE)
names(data_list)发布于 2017-09-15 02:42:05
据我所知,您从rwunderground包中提出的这个history_range函数需要一个天气地下API键。我去了该网站,甚至注册了它,但为了获得密钥(https://www.wunderground.com/weather/api)的电子邮件验证过程目前似乎不能正常工作。
相反,我转到set_location镜像(https://github.com/cran/rwunderground/blob/master/R/history.R),据我所知,该函数只接受一个字符串作为CRAN参数。文档中提供的示例如下
history(set_location(airport_code = "SEA"), "20130101") 所以你应该作为一个“循环”去做,而不是
sample_df <- as.vector(sample_df)
for(i in 1:length(sample_df)){
history_range(
set_location(airport_code = sample_df[[i]]),
date_start = "20170815", date_end = "20170822",
limit = 10, no_api = FALSE, use_metric = FALSE,
key = get_api_key(),
raw = FALSE, message = TRUE)
}如果这不起作用,请让我知道。(我打字的时候,也有人对这个问题给出了另一个答案。)
https://stackoverflow.com/questions/46225602
复制相似问题