Calculate group mean while excluding current observation using dplyr

前端 未结 1 1954
渐次进展
渐次进展 2020-12-06 13:35

Using dplyr (preferably), I am trying to calculate the group mean for each observation while excluding that observation from the group.

It seems that t

相关标签:
1条回答
  • 2020-12-06 14:14

    No need to define a custom function, instead we could simply sum all elements of the group, subtract the current value, and divide by number of elements per group minus 1.

    df %>% group_by(grouping) %>%
            mutate(special_mean = (sum(value) - value)/(n()-1))
    #   grouping value special_mean
    #      (chr) (int)        (dbl)
    #1         A     1          8.5
    #2         A     6          6.0
    #3         A    11          3.5
    #4         B     2          9.5
    #5         B     7          7.0
    
    0 讨论(0)
提交回复
热议问题