Join inherited scope with by in data.table Join inherited scope with by in data.table r r

Join inherited scope with by in data.table


Just a guess

library(data.table)dta <- data.frame(idx=c(1,2,3),                   vala=c(2,4,6),                  fdx=c('a','a','b'))dta <- data.table(dta)dtb <- data.frame(idx=c(1,4),                  valb=c(3,6))dtb <- data.table(dtb)setkey(dta,idx)setkey(dtb,idx)

So when you call

dta[dtb, sum(valb)]

it's kind of like calling

tmp <- dta[dtb]attach(tmp)sum(valb)detach(tmp)

However, if you call

dta[dtb, sum(valb), by=fdx]

then it's kind of like calling

tmp <- dta[dtb]# attach(tmp) : attach doesn't happensum(valb)# detach(tmp) : detach doesn't happen

The function doesn't know what to do with the additional arguments. For instance, this would also throw an error:

dta[dtb, class(fdx), sum(valb)]

However, this works

dta[dtb][, sum(valb), by=fdx]

which is kind of like

tmp <- dta[dtb]tmp[, sum(valb), by=fdx]

Like I said, this is just a guess as to why the function may not be working as expected.