can I switch the grouping variable in a single dplyr statement?

后端 未结 1 682
陌清茗
陌清茗 2021-01-05 11:22

Here\'s a simple example to illustrate the issue:

library(data.table)
dt = data.table(a = c(1,1,2,2), b = 1:2)

dt[, c := cumsum(a), by = b][, d := cumsum(a)         


        
相关标签:
1条回答
  • 2021-01-05 11:36

    Try this:

    > df %>% group_by(b) %>% mutate(c = cumsum(a)) %>%
    +        group_by(c) %>% mutate(d = cumsum(a))
    Source: local data frame [4 x 4]
    Groups: c
    
      a b c d
    1 1 1 1 1
    2 1 2 1 2
    3 2 1 3 2
    4 2 2 3 4
    

    Update

    With newer version of dplyr use %>% rather than %.% and ungroup is no longer needed (as per David Arenburg's comment).

    0 讨论(0)
提交回复
热议问题