2

I want to select rows in a data.table based on a variable set elsewhere and I am missing some key point of syntax.

library(data.table)
DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
DT

#this works as expected and does what I want
DT[y<3 & v >3] 
#but how do I pass my selection criteria in?
a1<-"y<3 & v>3"
a2<-quote(y<3 & v>3)
#so that one of these works?
DT[a1] #error
DT[a2] #error
DT[eval(a1)] #error
0

1 Answer 1

3

...One last test would have done it...

library(data.table)
DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
DT

#this works as expected and does what I want
DT[y<3 & v >3] 
#but how do I pass my selection criteria in?
a1<-"y<3 & v>3"
a2<-quote(y<3 & v>3)
#so that one of these works?
DT[a1] #error
DT[a2] #error
DT[eval(a1)] #error

DT[eval(a2)] #works
Sign up to request clarification or add additional context in comments.

1 Comment

If you have a character (like a1), you can also try DT[eval(parse(text=a1))]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.