John Richardson John Richardson - 3 months ago 6
R Question

Select rows in data table using a variable

I have a data table that I would like to filter rows based on a variable string. For example:

mtcars=as.data.table(mtcars)
mtcars[cyl>=4]


The above works but this doesn't:

str='cyl>=4'
mtcars[str]


I have tried [[str]] but that doesn't work either.

Thanks for your help

Answer

It's not best practice to get into the habit of using this. I would recommend rethinking whatever process generates the string. With that said you can do

mycars[eval(parse(text=str))]