首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何循环遍历城市列表,并在R中获得具有“weatherData”的给定日期的温度

如何循环遍历城市列表,并在R中获得具有“weatherData”的给定日期的温度
EN

Stack Overflow用户
提问于 2016-11-19 22:15:09
回答 1查看 171关注 0票数 1

我有以下df

代码语言:javascript
复制
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中数据的天气数据。

代码语言:javascript
复制
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获取具有以下功能的天气数据:

代码语言:javascript
复制
library(weatherData)
df <- getWeatherForDate("BOS", "2016-08-01")

有人能帮忙吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-19 22:31:38

以下是一种可能性:

代码语言:javascript
复制
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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40698506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档