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

查看:48
本文介绍了根据列条件以编程方式从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 通过粘贴在 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和进行比较将还原为带有& 子集的逻辑向量


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天全站免登陆