Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I substitute symbols in a language object?

Tags:

r

Suppose I have the following language object:

lang <- quote( f(x=a) )

and I want to substitute in 1 for a. How can I do this?

I would expect substitute to do what I want, but

substitute(lang, list(a=1))

just returns lang, while

substitute(f(x=a), list(a=1))

does in fact do what I expect.

like image 571
Kevin Ushey Avatar asked Oct 09 '13 20:10

Kevin Ushey


2 Answers

Use do.call:

do.call(substitute, list(lang, list(a=1)))

By using do.call, we force evaluation of the name `lang` to its actual underlying value, f(x=a). Then substitution is performed on f(x=a), rather than the name `lang`.

like image 132
Kevin Ushey Avatar answered Nov 04 '22 06:11

Kevin Ushey


If you have previously defined a in some environment (.GlobalEnv) as:

a <- 1

You can generally run:

construct(deconstruct_and_eval(lang))
f(x = 1)

For the definitions of these custom functions, see Generalized function to substitute all variables in the quote()d expression, if they exist in an environment

like image 42
Daniel Krizian Avatar answered Nov 04 '22 07:11

Daniel Krizian