3

I have an expression stored in a variable

a <- expression(10 + x + y)

I want to use substitute to fill the expression with x = 2

substitute(a, list(x=2))

But this returns a and a evaluates to expression(10 + x + y)

Ideally a would evaluate to expression(12 + y) (or (10 + 2 + y))

Is there any way to implement this behavior while using an expression stored in the variable a (mandated by other parts of my project)?

Bryce Frank
  • 667
  • 9
  • 22
  • Maybe worth pointing out that `substitute(expression(10 + x + y), list(x = 2))` works as desired, so the question is how to use substitute on an expression stored in a variable. (Implied by your title, but nice to be explicit.) – Gregor Thomas Dec 12 '17 at 19:35

3 Answers3

2

Use do.call. substitute won't descend into some objects but if you use a[[1]] here then it will work.

a <- expression(10 + x + y)
do.call("substitute", list(a[[1]], list(x = 2)))
## 10 + 2 + y
G. Grothendieck
  • 233,926
  • 16
  • 195
  • 321
2

You could do that with pryr if you can use an alternative (i.e. quote instead of expression):

a <- quote(10 + x + y)

library(pryr)
substitute_q(a, list(x=2))
#10 + 2 + y
LyzandeR
  • 35,731
  • 12
  • 70
  • 82
0

Maybe this one snippet can be useful

  x <- 1; y <- 2
  a <- expression(10 + x + y)
  eval(a)
Andrii
  • 2,469
  • 21
  • 26