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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With