[英]r data.table row subset with column name as a variable
Let's first create a simple data.table in r.我们先在r中创建一个简单的data.table。
dt=data.table(x1=1:5,
x2=11:21)
If we want to subset the data.table with conditions for rows, we can simple do, for example如果我们想用行的条件对 data.table 进行子集化,我们可以简单地做,例如
dt[x1==1]
Now my question is: what if the column name is a variable?现在我的问题是:如果列名是一个变量怎么办? I tried with:我试过:
var="x1"
dt[eval(var)==1,]
But this code doesn't work.但是这段代码不起作用。
eval
works with the following example: if we want to get the some columns by name (that is a variable). eval
适用于以下示例:如果我们想按名称(即变量)获取某些列。
dt[x1==1,eval(var),with=F]
I guess you are looking for get
:我猜你正在寻找get
:
library(data.table)
DT <- data.table(x1=1:11, x2=11:21)
var <- "x1"
DT[get(var)==1,]
An option with .SD
.SD
选项
DT[DT[, .SD[[var]] ==1]]
x1 x2
1: 1 11
which gives the same output as the accepted answer给出与接受的答案相同的 output
DT[get(var)==1,]
x1 x2
1: 1 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.