如何循环遍历城市列表并在 R 中使用 'weatherData' 获取给定日期的温度
How to loop through a list of cities and get temparature for given date with 'weatherData' in R
我有以下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")
有人可以帮忙吗?
有一种可能:
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
。
有必要查找车站代码,因为某些城市(如利物浦)可能位于不同的国家(在本例中为加拿大和英国)。我在 Weather Underground 网站上查看了利物浦的结果,结果是正确的。
我有以下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")
有人可以帮忙吗?
有一种可能:
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
。
有必要查找车站代码,因为某些城市(如利物浦)可能位于不同的国家(在本例中为加拿大和英国)。我在 Weather Underground 网站上查看了利物浦的结果,结果是正确的。