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
感謝您的幫助,它的工作完美。 –