简体   繁体   中英

data.table subsetting by a column defined in J

I would like to subset a data.table based on a column that I created in the j argument. I'm assuming that this is not possible given that I get "Error in eval(expr, envir, enclos) : object 'suma' not found" (example below), but maybe there is a way around it. Any suggestions?

thank you,

test <- data.table(A = c('a','b','c'), B = rep(c(1,2,3),4), C = c('typ1','typ2'))

head(test)
   A B    C
1: a 1 typ1
2: b 2 typ2
3: c 3 typ1
4: a 1 typ2
5: b 2 typ1
6: c 3 typ2

test[ suma > 4  , .(suma = sum(B)) , by = .(A,C)]

Error in eval(expr, envir, enclos) : object 'suma' not found

The way around it is to do the filtering after you created the column in a separate operation. In data.table this can be chained on to the end of the previous operation using [

test[ , .(suma = sum(B)) , by = .(A,C)][suma > 4]
#    A    C suma
# 1: c typ1    6
# 2: c typ2    6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM