Cumulative average by group

后端 未结 2 1315
长情又很酷
长情又很酷 2021-01-22 20:41

I want to compute trailing mean GPA by Name from the table below at each index. For example at index 9, I want to have the mean GPA for C from indices 3, 6, 9 and likewise for

2条回答
  •  野性不改
    2021-01-22 21:22

    Using dplyr:

    g <- data.frame(Name=rep(c("A","B","C"),3),
                GPA=c(5,6,7,5,6,6,7,6,3))
    
    g %>%
    group_by(Name) %>%
    mutate(cumu = lag(cummean(GPA), n = 0))
    

    Output:

    Source: local data frame [9 x 3]
    Groups: Name [3]
    
    Name   GPA     cumu
         
    1      A     5 5.000000
    2      B     6 6.000000
    3      C     7 7.000000
    4      A     5 5.000000 
    5      B     6 6.000000
    6      C     6 6.500000
    7      A     7 5.666667
    8      B     6 6.000000
    9      C     3 5.333333
    

提交回复
热议问题