在data.table中动态创建过滤器表达式(i) [英] create a filter expression (i) dynamically in data.table

查看:170
本文介绍了在data.table中动态创建过滤器表达式(i)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个data.table

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=" & ") ] 

但我仍然收到错误:

 Error in match(x, table, nomatch = 0L) : object 'x' not found

即使表达式evalutaed看起来不错:

even if the expression evalutaed looks good:

expression(x %in% c(1, 3) & z %in% c(12, 20))



(1,3)%c(1,3)& z%有没有办法来解决这个问题?

Is there a way to fix this?

推荐答案

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

Building expression instead of parsing it.

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

$ b b

呼叫呼叫((,x)呼叫((,y)可能不是必需的。

Calls call("(",x) and call("(",y) may not be necessary.

这篇关于在data.table中动态创建过滤器表达式(i)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆