1

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

John Richardson
  • 676
  • 8
  • 24
  • 2
    Use `str=quote(cyl>=4); mtcars[eval(str)]`. The FAQ is considered part of the docs and should probably be read in full before asking about basic functionality. This is question 1.16: https://rawgit.com/wiki/Rdatatable/data.table/vignettes/datatable-faq.html#ok-but-i-dont-know-the-expressions-in-advance.-how-do-i-programatically-pass-them-in The other resources mentioned on the support page are probably also worth a look: https://github.com/Rdatatable/data.table/wiki/Support – Frank Aug 17 '16 at 20:01
  • I don't think this is a duplicate question. The only questions I could find were with j regarding columns. The FAQ referred to is not clear on how to do this for i. Your answer in the comment does not work for me because it requires the "cyl>=4" be hard coded instead of a variable. The answer provided by Dean does work. – John Richardson Aug 17 '16 at 21:26
  • Sure. You want this one? http://stackoverflow.com/questions/1743698/evaluate-expression-given-as-a-string The eval-parse-text path is not unique to data.table and it's generally discouraged, fyi: http://stackoverflow.com/q/13649979/ Regarding the FAQ not covering `i`, you could bring that up as feedback / a feature request using the support link above. I'm sure the package authors are interested in gaps new users are finding in the vignettes. – Frank Aug 17 '16 at 21:59
  • Hmmm... maybe I am confused but the question was about how to use a a var in i for a data table. If I knew the existence of eval(parse()) I wound't have asked the question. I am assuming I am not the only one who didn't know, and therefore someone looking to solve this issue as it relates to data tables would be able to find a quick answer and learn. Just my 2 cents – John Richardson Aug 18 '16 at 00:08

1 Answers1

2

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))]
Dean MacGregor
  • 11,847
  • 9
  • 34
  • 72