通过折叠r中的两列来计算变量的平均值

时间:2018-12-22 19:31:59

标签: r

我希望找到每年每个季节的平均值。每年被观察4次。季节是两个,但重复两次,如下所示

year=rep(c(1990:1992),each=4)
season=c("W","D","W","D","W","W","D","D","D","W","W","D")
temp=c(28,25,26,21,28,25,20,20,20,35,28,21)
df=data.frame(year,season,temp)

给出

   year season temp
1  1990      W   28
2  1990      D   25
3  1990      W   26
4  1990      D   21
5  1991      W   28
6  1991      W   25
7  1991      D   20
8  1991      D   20
9  1992      D   20
10 1992      W   35
11 1992      W   28
12 1992      D   21

我想折叠此数据以使每年的两个季节的平均值如下所示

  year season avgtemp
1 1990      D    23.0
2 1990      W    27.0
3 1991      D    20.0
4 1991      W    25.1
5 1992      D    20.5
6 1992      W    31.5

我怎么能得到这个?

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

    aggregate(df[, 3], df[, 1:2], mean)

答案 1 :(得分:0)

library(tidyvere) 
df %>% 
     group_by(year,season) %>% 
   summarise(avgtemp=mean(temp))
# A tibble: 6 x 3
# Groups:   year [?]
   year season avgtemp
  <int> <fct>    <dbl>
1  1990 D         23  
2  1990 W         27  
3  1991 D         20  
4  1991 W         26.5
5  1992 D         20.5
6  1992 W         31.5