data.table rejects to create new column when used in a chain

Viewed 45

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
1 Answers

Pay attention to the order. You can try

aa[,c:=cumsum(a), by=.(b)][order(a,b)]

In this line aa[order(a,b)][,c:=cumsum(a), by=.(b)], it can be viewed as tmp <- aa[order(a,b)], tmp[,c:=cumsum(a), by=.(b)]. Column c is indeedly created but not in original aa if you run aa[order(a,b)][,c:=cumsum(a), by=.(b)][] to check.

Related