Reputation: 738
I want to use as quote (or expression) as i
in a data.table. But it seems to be not possible.
Here is a minimal example:
library(data.table)
dt <- data.table(a = 1:10)
dt[a == 5,] # Everything well
dt[quote(a == 5),] # Error: i has not evaluated to logical, integer or double
dt[expression(a == 5),] # Error: i has not evaluated to logical, integer or double
The help page of data.table states for i
:
Integer, logical or character vector, single column numeric matrix, expression of column names, list, data.frame or data.table.
So I think, it should work with expressions. What is my mistake? Or is there a way to "unquote" the quote?
Upvotes: 2
Views: 962
Reputation: 738
For reasons of completeness, here is the answer of @nicola posted as comment below the question:
The expression or quote should be enclosed via eval()
. For the examples in the question it looks like:
library(data.table)
dt <- data.table(a = 1:10)
dt[a == 5,] # Everything well
dt[eval(quote(a == 5)),] # Now, it works
dt[eval(expression(a == 5)),] # Now, it works
The secret seems to be that R evaluates the arguments within the environment of the function and not within the context the function is called.
Upvotes: 1