如何基于R中的多列进行汇总?

How to summarize based on multiple columns in R?

我想根据“年”、“月”和“subdist_id”列来汇总数据集。对于每个 subdist_id,我想获得 11、12、1、2 月份但不同年份的“降雨量”的平均值。例如,对于 subdist_id 81,2004 年的平均降雨量值将是 2004 年第 11、12 个月和 2005 年第 1、2 个月的平均降雨量。

虽然我在网上仔细搜索过,但我不知道该怎么做。

假设您的数据集名为 df。这是您要找的吗?

df %>% group_by(subdist_id, year) %>% summarise(Rainfall = mean(Rainfall))

扩展@Bloxx 的回答并结合我的评论:

# Set up example data frame:
df = data.frame(year=c(rep.int(2004,2),rep.int(2005,4)), 
                month=((0:5%%4)-2)%%12+1,
                Rainfall=seq(.5,by=0.15,length.out=6))

现在使用mutate创建year2变量:

df %>% mutate(year2 = year - (month<3)*1) # or similar depending on the problem specs

现在应用 groupby/summarise 操作:

df %>% mutate(year2 = year - (month<3)*1) %>% 
       group_by(year2) %>% 
       summarise(Rainfall = mean(Rainfall))

我想你可以简单地这样做:

df %>% filter(months %in% c(1,2,11,12)) %>%
  group_by(subdist_id, year=if_else(months %in% c(1,2),year-1,year)) %>% 
  summarize(meanRain = mean(Rainfall))

输出:

  subdist_id  year meanRain
       <dbl> <dbl>    <dbl>
1         81  2004    0.611
2         81  2005    0.228

输入:

df = data.frame(
  subdist_id = 81,
  year=c(2004,2004, 2005, 2005, 2005, 2005),
  months=c(11,12,1,2,11,12),
  Rainfall = c(.251,.333,.731,1.13,.111,.346)
)