Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lapply using colnames with data.table

Tags:

r

data.table

I am trying to pass different specific colnames to a data.table inside a loop but I can't figure how to do it or if it possible.

## Simple example 

dt <- data.table(one = c(1:4), two = c(5:8), three = c(10:13))

dt[one > 2]

col = "one"

dt[col > 2] ## does not work
## Eventually I would like to do something like this:

lapply(colnames(dt)[1:2], function(x){
  
  dt[x > 2]
  
})

I thought of working with SDcols but I don't see how to use it in data.table's i or j the way I want.

Is there a way to achieve this ?

like image 556
Paul Endymion Avatar asked Sep 25 '26 21:09

Paul Endymion


1 Answers

Use get()

lapply(colnames(dt)[1:2], function(x){
  
  dt[get(x) > 2]
  
})
#> [[1]]
#>    one two three
#> 1:   3   7    12
#> 2:   4   8    13
#> 
#> [[2]]
#>    one two three
#> 1:   1   5    10
#> 2:   2   6    11
#> 3:   3   7    12
#> 4:   4   8    13
like image 143
mnist Avatar answered Sep 28 '26 16:09

mnist