This is an extremely simple question, but again I'm confounded by the data.table
syntax.
If I have a string representing a column name -- such as column <- "x"
-- how do I return just the rows that match a logical condition on that column?
In a data.frame
, if I wanted to return all rows of the table where column x
equaled 1
, I'd write df[df[,column] == 1,]
.
How do I write that efficiently in a data.table
?
(Note, dt[x == 1]
works fine, but not if you use a string like column
representing the name of that column.)
The answers here are close but do not seem to be enough to answer this question.
dt[get(column) == 1]
seems to work -- is that the most efficient method?
One way of doing this:
dt[eval(as.name(column)) == 1, ]
See section 1.6 of the FAQ on how one could create expressions and evaluate them within the frame of dt
(although the FAQ explains it in the context of j
, constructing expressions and evaluating them is also valid in the context of i
, as shown above).
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