在 data.table 中动态创建过滤表达式 (i)

ags*_*udy 4 r data.table

有一个data.table

library(data.table)
dd <- data.table(x=1:10,y=10:1,z=20:20)
Run Code Online (Sandbox Code Playgroud)

我可以使用过滤它

dd[x %in% c(1, 3) & z %in% c(12, 20)]
   x  y  z
1: 1 10 20
2: 3  8 20
Run Code Online (Sandbox Code Playgroud)

现在我想动态创建相同的过滤器。这是我到目前为止所尝试过的:

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=" & ") ] 
Run Code Online (Sandbox Code Playgroud)

但我仍然收到错误:

 Error in match(x, table, nomatch = 0L) : object 'x' not found
Run Code Online (Sandbox Code Playgroud)

即使评估的表达式看起来不错:

expression(x %in% c(1, 3) & z %in% c(12, 20))
Run Code Online (Sandbox Code Playgroud)

有没有办法来解决这个问题?

jan*_*cki 5

构建表达式而不是解析它。

library(data.table)
dd = data.table(x=1:10,y=10:1,z=20:20)
AndIN = function(cond){
    Reduce(
        function(x, y) call("&", call("(",x), call("(",y)),
        lapply(names(cond), function(var) call("%in%", as.name(var), cond[[var]]))
    )
}
cond = list(x=c(1,3),z=c(12,20))
AndIN(cond)
#(x %in% c(1, 3)) & (z %in% c(12, 20))
dd[eval(AndIN(cond))]
#   x  y  z
#1: 1 10 20
#2: 3  8 20
Run Code Online (Sandbox Code Playgroud)

打电话call("(",x)可能call("(",y)没有必要。