2

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?

Guybrush
  • 710
  • 7
  • 12
  • Why would you want to use quote inside the square brackets? – Marco De Virgilis Jan 11 '19 at 09:05
  • The quote comes as parameter to the function and should be passed to the data.table. The function itself manipulates the quote and add some other terms. – Guybrush Jan 11 '19 at 09:07
  • 1
    Can you provide a more complete example of what you would like to achieve? – Marco De Virgilis Jan 11 '19 at 09:09
  • 1
    Enclose the `expression` with `eval()`. For instance: `dt[eval(expression(a == 5)),]`. – nicola Jan 11 '19 at 09:14
  • So simple. I thought I tried it before but the result shows me the different. Thank you very much @nicola – Guybrush Jan 11 '19 at 09:18
  • For my understanding: Why does ```eval()``` works in this context? If I try ```eval(quote(a + 6))``` outside the data.table it gives me an error "object 'x' not found" as I expected since ```eval``` immediately tries to evaluate the expression. Why does the ```eval()``` within the data.table brackets is not evaluated immediately? – Guybrush Jan 11 '19 at 09:40

1 Answers1

1

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.

Guybrush
  • 710
  • 7
  • 12