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), by = 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
Attempting to do the same in dplyr
I fail because the first group_by
is persistent and the grouping is by both b
and c
:
df = data.frame(a = c(1,1,2,2), b = 1:2)
df %.% group_by(b) %.% mutate(c = cumsum(a)) %.%
group_by(c) %.% mutate(d = cumsum(a))
# a b c d
#1 1 1 1 1
#2 1 2 1 1
#3 2 1 3 2
#4 2 2 3 2
Is this a bug or a feature? If it's a feature, then how would one replicate the data.table
solution in a single statement?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With