快速免责声明——几天前我刚刚拿起 R,几乎没有任何编程经验,所以如果这个问题很愚蠢或代码看起来很糟糕,我深表歉意。(可能是)。
上代码!所以我使用了这个博客中的一些代码,我将这些代码重新用于尝试一些有趣的基于天气的统计建模。
我编写的用于下拉天气数据的函数如下所示:
getHistoricalWeather <- function(weatherstation, senddate) {
base.url <- 'http://api.wunderground.com/api/{MY API IS HERE}/'
final.url <- paste(base.url, 'history_', senddate, '/q/', weatherstation, '.json',sep='')
conn <- url(final.url)
raw.data <- readLines(conn, n=-1L, ok=TRUE)
weather.data <- fromJSON(paste(raw.data, collapse=""))
close(conn)
return(weather.data)
}
之后,我尝试遍历 10 个单独的日期并提取每个日期的天气数据,找到基于特定时间、平均湿度和总降雨量之间的平均温度。它们的日期保存在一个名为 checkdate 的变量中。
checkdate
[1] "20130628" "20130611" "20130612" "20130613" "20130614" "20130615" "20130616" "20130617" "20130618" "20130619"
过滤掉特定信息的函数如下所示:
atwaters_cleanup <- function() {
average_temperature <- 0
average_hum <- 0
total_precipi <- 0
for (i in seq_along(gotweatherdata$history$observations)) {
if (as.numeric(gotweatherdata$history$observations[[i]]$date$hour) >= 6 && as.numeric(gotweatherdata$history$observations[[i]]$date$hour) < 18) {
average_temperature <- c(average_temperature,as.numeric(gotweatherdata$history$observations[[i]]$tempi))
average_hum <- c(average_temperature,as.numeric(gotweatherdata$history$observations[[i]]$hum))
if (as.numeric(gotweatherdata$history$observations[[i]]$precipi) > 0) {total_precipi <- c(total_precipi,as.numeric(gotweatherdata$history$observations[[i]]$precipi))}
}
}
average_temperature <- sum(average_temperature) / length(average_temperature)
average_hum <- sum(average_hum) / length(average_hum)
total_precipi <- sum(total_precipi)
return(c(average_temperature, average_hum, total_precipi))
}
最后,有问题的 for 循环如下所示:
pull_day <- function() {
atwaters_historical_data <- data.frame()
for (i in 1:length(checkdate)) {
gotweatherdata <- getHistoricalWeather("KBWI",checkdate[i])
atwaters_historical_data <- rbind(atwaters_historical_data, atwaters_cleanup())
}
return(atwaters_historical_data)
}
然而,我遇到的问题是 for 循环似乎只返回同一天的 10 个实例:
X70.9642857142857 X69.8333333333333 X0
1 70.96429 69.83333 0
2 70.96429 69.83333 0
3 70.96429 69.83333 0
4 70.96429 69.83333 0
5 70.96429 69.83333 0
6 70.96429 69.83333 0
7 70.96429 69.83333 0
8 70.96429 69.83333 0
9 70.96429 69.83333 0
10 70.96429 69.83333 0
但是,如果我在 for 循环之外手动尝试相同的命令,它似乎工作正常。在示例中,我只是将 checkdate[1] 更改为 checkdate[2]
> gotweatherdata <- getHistoricalWeather("KBWI",checkdate[1])
> atwaters_historical_data <- rbind(atwaters_historical_data,atwaters_cleanup())
> atwaters_historical_data
X74.2153846153846 X74.5571428571428 X0.02
1 74.21538 74.55714 0.02
> gotweatherdata <- getHistoricalWeather("KBWI",checkdate[2])
> atwaters_historical_data <- rbind(atwaters_historical_data,atwaters_cleanup())
> atwaters_historical_data
X74.2153846153846 X74.5571428571428 X0.02
1 74.21538 74.55714 0.02
2 70.96429 69.83333 0.00
我已经尝试过测试 for 循环,并且我相当确定它将正确的数字插入 checkdate[x](1 到 10),但我不断得到相同的重复结果。抱歉,这看起来一团糟,提前感谢您的帮助!