canary_in_the_data_mine
canary_in_the_data_mine

Reputation: 2393

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.

Upvotes: 5

Views: 116

Answers (2)

BrodieG
BrodieG

Reputation: 52657

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

Upvotes: 2

canary_in_the_data_mine
canary_in_the_data_mine

Reputation: 2393

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

Upvotes: 4

Related Questions