2017-09-14 105 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

非常感謝。我會盡力處理你的指導。 –