首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用r计算气象站数据的平均值

用r计算气象站数据的平均值
EN

Stack Overflow用户
提问于 2014-08-29 04:55:05
回答 4查看 3.1K关注 0票数 1

我正在使用一个大约800个气象站的数据集,每个气象站从1986年到2014年的月气温值。数据分为三列:(1)桩号名称、(2)日期(年和月)和(3) Temp。一般而言,数据如下所示:

代码语言:javascript
复制
STATION    DATE    TEMP
Station 1  198601  -15
Station 1  198602  -16
Station 1  201401  -10
Station 1  201402  -14
Station 2  198601  -11
Station 2  198602  -9
Station 2  201401  -5
Station 2  201402  -4

我需要提取不同年份范围内给定月份的每个气象站的平均温度。例如,如果我需要知道1986-1990年间每个气象站7月份的平均气温。我的理想输出是一个新的列表或数据帧,它根据我指定的日期范围给出每个站点的平均温度。

我确信这可以使用for循环来完成,但我不太擅长创建这样的代码。任何建议都将不胜感激。

EN

回答 4

Stack Overflow用户

发布于 2014-08-29 05:13:44

使用dplyr代替数据表

代码语言:javascript
复制
weather <- data.frame(station = c("Station 1", "Station 1", "Station 1", "Station 1",
                              "Station 2", "Station 2", "Station 2", "Station 2"),
                  date = c(198601, 198602, 201401, 201402, 198601, 198602, 201401, 201402),
                  temp = c(-15, -16, -10, -14, -11, -9, -5, -4))


library(dplyr)
library(stringr)
# get month and year columns in data
weather <- mutate(weather,
              year = str_extract(date, "\\d{4}"),
              month = str_extract(date, "\\d{2}$"))

# get the mean for each station for each month
mean_station <- group_by(weather, station, month) %>%
  summarise(mean_temp = mean(temp, na.rm = T))

如果只需要在特定的日期范围内执行此操作,则可以按年份添加筛选器

代码语言:javascript
复制
mean_station <- group_by(weather, station, month) %>%
  filter(year >= 1986, year <= 2015) %>%
  summarise(mean_temp = mean(temp, na.rm = T))
票数 2
EN

Stack Overflow用户

发布于 2014-08-29 05:03:33

像这样的东西...?

代码语言:javascript
复制
> df$month <- substr(df$DATE, 5, 6)
> result <- aggregate(TEMP~STATION+month, mean, data=df)
> data.frame(Year=unique(substr(df$DATE, 1, 4)), result)
  Year  STATION month  TEMP
1 1986 Station1    01 -12.5
2 2014 Station2    01  -8.0
3 1986 Station1    02 -15.0
4 2014 Station2    02  -6.5
票数 1
EN

Stack Overflow用户

发布于 2014-08-29 05:07:49

或者也许

代码语言:javascript
复制
library(data.table)
setDT(df)[, list(MeanTemp = mean(TEMP)), 
                by = list(STATION, Mon = substr(DATE, 5, 6))]

#      STATION Mon MeanTemp
# 1: Station 1  01    -12.5
# 2: Station 1  02    -15.0
# 3: Station 2  01     -8.0
# 4: Station 2  02     -6.5
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25557848

复制
相关文章

相似问题

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