I am new to data.table packcage and become confused about its chaining behavior. Suppose we have the following code:
aa <- data.table(a=c(1,2,3), b = c("a","b","b"))
aa[order(a,b)][,c:=cumsum(a), by=.(b)]
> aa
a b
1: 1 a
2: 2 b
3: 3 b
Column c is not created.
But if we write the code seperately without chaining, c can be genereted:
aa <- data.table(a=c(1,2,3), b = c("a","b","b"))
aa[order(a,b)]
a b
1: 1 a
2: 2 b
3: 3 b
aa[,c:=cumsum(a), by=.(b)]
> aa
a b c
1: 1 a 1
2: 2 b 2
3: 3 b 5
So why does this happen? How can I write the chain code correctly using data.table?
Thank you a lot!
Below is new
I noticed that, if we assign it to a new dataframe, it worked again:
aa <- data.table(a=c(1,2,3), b = c("a","b","b"))
bb <- aa[order(a,b)][,c:=cumsum(a), by=.(b)]
> bb
a b c
1: 1 a 1
2: 2 b 2
3: 3 b 5