根据列标准以编程方式从 Data.table 中选择行 [英] Select rows from Data.table programmatically based on column criteria

查看:16
本文介绍了根据列标准以编程方式从 Data.table 中选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于如何根据列中的值以编程方式从 data.table 中选择行的问题.

I have a question on the way to select programmatically the rows from a data.table based on values from columns.

假设我有下面的 Data.table

Let say I have below Data.table

library(data.table)
DT <- data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)

现在我想选择 y = 3 和 v = 2 的行

通常我可以使用下面的代码

Normally I can use below code

> DT[y==3& v==2]
   x y v
1: a 3 2

但在我的情况下,这样的选择标准本身就是一个变量,并放入不同的 DF

But in my case, such selection criteria is itself a variable, and put in a different DF

> DF = data.frame('1' = c('y', 'v'), '2' = c(3,2)); DF
  X1 X2
1  y  3
2  v  2

在这种情况下,上面的 X2 的值会改变,偶数行也是可变的(即假设我有一个更大的 DT 有更多的列,一些额外的DF 中的行可能基于 DF 的生成标准)

In this case, the value of X2 above will change, even number of rows is also variable (i.e. assuming I have a bigger DT with more columns, some additional rows in DF might come based on the generation criteria of DF)

有没有办法使用 DF 以编程方式选择 DT 中的行?

Is there any way to use DF to select rows in DT programmatically?

推荐答案

一个选项是 eval 通过 paste 'DF' 的列创建一个表达式

An option is to eval by pasteing the columns of 'DF' to create an expression

DT[eval(parse(text= paste(DF$X1, DF$X2,  sep="==", collapse=" & ")))]
#   x y v
#1: a 3 2

<小时>

或者我们可以将 .SDcols 指定为 'X1' 列,然后将 .SD 与 'X2' 和 Reduce 进行比较到带有 & 的逻辑 vector,对行进行子集化


or we can specify the .SDcols as the 'X1' column, then compare the .SD with 'X2' and Reduce it to a logical vector with &, subset the rows

DT[DT[, Reduce(`&`, Map(`==`, .SD, DF$X2)),.SDcols = as.character(DF$X1)]]
#   x y v
#1: a 3 2

这篇关于根据列标准以编程方式从 Data.table 中选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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