2017-09-14 108 views
0

捕获的天气数据,我想执行环路捕获从使用以下代码的多个站的气象数据:R:循环从多个站

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) 

它不会工作。

回答

1

目前,您正在将整个向量(多个字符值)传递给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) 
+0

太棒了!乐意效劳。并且请注意在StackOverflow上说[谢谢](https://meta.stackexchange.com/a/5235)的特殊方式! – Parfait

+0

再次感谢您的帮助。作为最后一个问题,我如何将它保存为csv文件或其他文件? –

+0

我不知道API返回的是什么。如果是数据帧/矩阵,请参见在'write.csv'中添加的上述更新中的扩展函数。 – Parfait

0

我认为你从rwunderground软件包中提出的history_range函数,据我所知,需要一个天气地下API密钥。我去了网站,甚至注册了它,但为了得到一个密钥(https://www.wunderground.com/weather/api)的电子邮件验证过程目前似乎没有正常工作。

相反,我去了CRAN镜像(https://github.com/cran/rwunderground/blob/master/R/history.R),从我的理解,该函数只接受一个字符串作为set_location参数。该文档中提供的例子是

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) 
} 

如果这不起作用,让我知道。 (Ack,当我打字时,有人也给出了这个问题的另一个答案。)

+0

非常感谢。我会尽力处理你的指导。 –