Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ==1 on a column defined by a variable

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.

like image 443
canary_in_the_data_mine Avatar asked Jan 28 '14 01:01

canary_in_the_data_mine


2 Answers

dt[get(column) == 1] seems to work -- is that the most efficient method?

like image 91
canary_in_the_data_mine Avatar answered Oct 13 '22 10:10

canary_in_the_data_mine


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).

like image 43
BrodieG Avatar answered Oct 13 '22 12:10

BrodieG