2016-11-19 62 views
0

我有一個名爲getWeatherForMonth的函數,它將開始日期和結束日期作爲每個月結果的數據框。我有另一個方法getWeatherForRange需要一個範圍的數據幀。我需要爲「日期」中的每一行調用getWeatherForMonth,並將結果合併到一個數據框中。我像下面一樣使用了mapply,但它並沒有合併所得到的數據幀。調用數據框中項目數量的函數並將結果合併在一起

library(RJSONIO) 

    getWeatherForMonth <- function(start.date, end.date) { 
     url <- "http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=PUT-YOUR-KEY-HERE&q=London&format=json&date=%s&enddate=%e&tp=24" 
     url <- gsub("%s", start.date, url) 
     url <- url <- gsub("%e", end.date, url) 

     data <- fromJSON(url) 
     weather <- data$data$weather 
     GMT <- sapply(weather, function(x){as.character(x[1])}) 
     Max.TemperatureC <- sapply(weather, function(x){as.numeric(x[3])}) 
     Min.TemperatureC <- sapply(weather, function(x){as.numeric(x[4])}) 
     Wind.SpeedKm.h <- sapply(weather, function(x){as.numeric(x$hourly[[1]]$windspeedKmph[1])}) 
     Precipitationmm <- sapply(weather, function(x){as.numeric(x$hourly[[1]]$precipMM[1])}) 
     DewPointC <-sapply(weather, function(x){as.numeric(x$hourly[[1]]$DewPointC[1])}) 
     Wind.Chill <-sapply(weather, function(x){as.numeric(x$hourly[[1]]$WindChillC[1])}) 
     Cloud.Cover <-sapply(weather, function(x){as.numeric(x$hourly[[1]]$cloudcover[1])}) 
     Description <-sapply(weather, function(x){as.character(x$hourly[[1]]$weatherDesc[1])}) 
     Humidity <- sapply(weather, function(x){as.numeric(x$hourly[[1]]$humidity[1])}) 
     Feels.LikeC <- sapply(weather, function(x){as.numeric(x$hourly[[1]]$FeelsLikeC[1])}) 

     df <- data.frame(GMT, Max.TemperatureC, Min.TemperatureC, Wind.SpeedKm.h, Precipitationmm, DewPointC, Wind.Chill, Cloud.Cover, Description, Humidity, Feels.LikeC) 

     return(df) 
    } 

    getWeatherForRange <- function(dates) { 
     df <- mapply(getWeatherForMonth, dates$start.date, dates$end.date) 

     return(df) 
    } 

    start.date <- seq(as.Date("2015-01-01"), length=12, by="1 month") 
    end.date <- seq(as.Date("2015-02-01"),length=12,by="months") - 1 
    dates.2015 <- data.frame(start.date, end.date) 

    data <- getWeatherForRange(dates) 
    View(data) 

輸出看起來像這樣 Screenshot of the current output

回答

0

考慮使用Map()。具體而言,在您的getWeatherForRange函數中,使用Map(),它實際上是mapply()的非簡化版本的包裝,相當於mapply(..., SIMPLIFY=FALSE)。默認情況下,mapply()返回矢量,矩陣或更高維的數組。但是你需要一個數據框(即一個列表對象)的返回。

此更新的函數將返回一個數據幀列表,您可以稍後運行一個do.call(rbind, ...)(假設每個df中的所有列都一致)將所有dfs堆疊在一起以獲得最終數據幀。

getWeatherForRange <- function(dates) { 
    # EQUIVALENT LINES 
    dfList <- Map(getWeatherForMonth, dates$start.date, dates$end.date) 
    # dfList <- mapply(getWeatherForMonth, dates$start.date, dates$end.date, SIMPLIFY = FALSE) 
    return(dfList) 
} 

start.date <- seq(as.Date("2015-01-01"), length=12, by="1 month") 
end.date <- seq(as.Date("2015-02-01"), length=12, by="months") - 1 
dates <- data.frame(start.date, end.date) 

datalist <- getWeatherForRange(dates)   # DATAFRAME LIST 
data <- do.call(rbind, datalist)    # FINAL DATA FRAME 
+0

感謝您的幫助,它的工作完美。 –

相關問題