按 R 中的特定年份汇总

Aggregate by specific year in R

抱歉,如果这个问题已经在 SO 上得到解决,但我似乎还无法找到快速的解决方案。

我正在尝试按特定年份汇总数据集。我的数据框包含 10 年期间的每小时气候数据。

head(df)
#  day month year hour rain temp pressure wind
#1   1     1 2005    0    0  7.6     1016   15
#2   1     1 2005    1    0  8.0     1015   14
#3   1     1 2005    2    0  7.7     1014   15
#4   1     1 2005    3    0  7.8     1013   17
#5   1     1 2005    4    0  7.3     1012   17
#6   1     1 2005    5    0  7.6     1010   17

为了根据上述数据集计算日均值,我使用了这个聚合函数

g <- aggregate(cbind(temp,pressure,wind) ~ day + month + year, d, mean)
options(digits=2)

head(g)
#  day month year temp pressure wind
#1   1     1 2005  6.6     1005   25
#2   2     1 2005  6.5     1018   25
#3   3     1 2005  9.7     1019   22
#4   4     1 2005  7.5     1010   25
#5   5     1 2005  7.3     1008   25
#6   6     1 2005  9.6     1009   26

不幸的是,我得到了一个跨越整整 10 年(2005 年到 2014 年)的庞大数据集。我想知道是否有人能够帮助我调整上述聚合代码,以便我能够汇总特定年份的每日平均值,而不是一次滑动所有平均值?

您可以在 aggregate

中使用 subset 参数
aggregate(cbind(temp,pressure,wind) ~ day + month + year, df, 
                     subset=year %in% 2005:2014, mean)

Dplyr也做得很好

library(dplyr)

df %>% 
filter(year==2005) %>% 
group_by(day, month, year) %>% 
summarise_each(funs(mean), temp, pressure, wind)