我有以下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$City获取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")有人能帮忙吗?
发布于 2016-11-19 22:31:38
以下是一种可能性:
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第一步是使用sub和getStationCode函数获取不同城市的代码。然后,我们得到温度平均值的向量,最后,我们用正确的列名创建data.frame city2。
有必要查找车站代码,因为一些城市(如利物浦)可能位于不同的国家(这里是加拿大和英国)。我在天气网站上查看了利物浦的结果,结果是正确的。
https://stackoverflow.com/questions/40698506
复制相似问题