1

我有以下df

city <- data.frame(City = c("London", "Liverpool", "Manchester","London", "Liverpool", "Manchester"),
                   Date = c("2016-08-05","2016-08-09","2016-08-10", "2016-09-05","2016-09-09","2016-09-10"))

我想遍历它并通过city$Cityfor the data in获取天气数据city$Date

city <- data.frame(City = c("London", "Liverpool", "Manchester","London", "Liverpool", "Manchester"),
                   Date = c("2016-08-05","2016-08-09","2016-08-10", "2016-09-05","2016-09-09","2016-09-10"),
                   Mean_TemperatureC = c("15","14","13","14","11","14"))

目前我正在使用weatherData以下功能获取天气数据:

library(weatherData)
df <- getWeatherForDate("BOS", "2016-08-01")

有人可以帮忙吗?

4

1 回答 1

3

这是一种可能性:

temp <- as.matrix(city)
codes <- sapply(1:nrow(city), function(x) getStationCode(city[x,1], "GB")[[1]])
station <- sub("^[[:print:]]+\\s([A-Z]{4})\\s[[:print:]]+", "\\1", codes)

temp[, 1] <- station

temperature <- sapply(1:nrow(temp), function(x) {getWeatherForDate(temp[x, 1], temp[x, 2])$Mean_TemperatureC})
city2 <- setNames(cbind(city, temperature), c(colnames(city), "Mean_TemperatureC"))

city2
#        City       Date Mean_TemperatureC
# 1     London 2016-08-05                14
# 2  Liverpool 2016-08-09                14
# 3 Manchester 2016-08-10                13
# 4     London 2016-09-05                20
# 5  Liverpool 2016-09-09                18
# 6 Manchester 2016-09-10                13

第一步是获取具有subgetStationCode功能的不同城市的代码。然后我们得到温度平均值的向量,最后,我们创建了 data.frame city2,具有正确的列名。

有必要查找车站代码,因为某些城市(如利物浦)可能位于不同的国家(在这种情况下为加拿大和英国)。我在 Weather Underground 网站上查看了利物浦的结果,结果是正确的。

于 2016-11-19T22:31:38.700 回答