Software subset of data table in R

This seems like a very simple question, but its solution eluded me about 90 minutes of trying, searching and reading manuals and online.

Say I have data.table:

DT<-data.table(a=runif(n = 10),b=runif(n = 10),c=runif(n = 10)) 

Obviously something like this works:

 DT[a > 0.5] 

and gives me a subset of DT, where the values ​​in column "a" are greater than 0.5. But what if I want to be a little more flexible (because a subset is built into the larger procedure).

What I would like to do is make this proto function:

 flexSubset<-function(sColumnToSubset,dMin){ subs<-DT[sColumnToSubset>dMin] return(subs) } 

I tried without success, among many others ...

 with=FALSE 

Any suggestions? Thanks so much for your time in advance!

+5
source share
1 answer

If you want to pass a string, do the following:

 flexSubset = function(sColumnToSubset, dMin) DT[get(sColumnToSubset) > dMin] flexSubset("a", 0.5) 

If you want to convey an invaluable expression, then:

 flexSubset = function(sColumnToSubset, dMin) { lhs = substitute(sColumnToSubset) DT[eval(lhs) > dMin] } flexSubset(a, 0.5) flexSubset(a / b, 0.5) 
+8
source

Source: https://habr.com/ru/post/1216625/


All Articles