我有一个名为getWeatherForMonth的函数,它接受一个开始日期和结束日期,并作为每个月结果的数据框返回。我有另一个getWeatherForRange方法,它接受范围的数据帧。我需要为" date"中的每一行调用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 :(得分: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