1

Let's first create a simple data.table in r.

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

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).

dt[x1==1,eval(var),with=F]
John Smith
  • 1,604
  • 4
  • 18
  • 45
  • 1
    Possible duplicate https://stackoverflow.com/questions/12391950/select-assign-to-data-table-when-variable-names-are-stored-in-a-character-vect – Ronak Shah Aug 26 '21 at 12:34

2 Answers2

1

I guess you are looking for get:

library(data.table)

DT <- data.table(x1=1:11, x2=11:21)
var <- "x1"
DT[get(var)==1,]
ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
1

An option with .SD

 DT[DT[, .SD[[var]] ==1]]
   x1 x2
1:  1 11

which gives the same output as the accepted answer

 DT[get(var)==1,]
   x1 x2
1:  1 11
akrun
  • 874,273
  • 37
  • 540
  • 662