Having a data.table
library(data.table)
dd <- data.table(x=1:10,y=10:1,z=20:20)
I can filter it using
dd[x %in% c(1, 3) & z %in% c(12, 20)]
x y z
1: 1 10 20
2: 3 8 20
Now I would like to create the same filter dynamically. This what I have tried so far:
cond <- list(x=c(1,3),z=c(12,20))
vars <- names(cond)
## dd[get(vars[[1]]) %in% cond[[1]] & get(vars[[2]]) %in% cond[[2]]]
EVAL = function(...){
expr <- parse(text=paste0(...))
print(expr)
eval(expr)
}
dd[ EVAL(vars, " %in% ", cond, collapse=" & ") ]
But I still get an error:
Error in match(x, table, nomatch = 0L) : object 'x' not found
even if the expression evalutaed looks good:
expression(x %in% c(1, 3) & z %in% c(12, 20))
Is there a way to fix this?
EVAL = function(x, vars, cond){ setkeyv(x, vars) ; x[do.call(CJ, cond), nomatch = 0L] } ; EVAL(dd, vars, cond)dd[rowSums(mapply(`%in%`, dd[names(cond)], cond)) == length(cond), ]in basecondand then join the result:dd[do.call(CJ,cond), on=names(cond), nomatch=0](Oh, I see David posted something similar above.)