Search code examples
rexpressionapollonestquote

How to nest an expression or quote in another expression or quote?


Let's say I have

first <- quote(beta_a*a + beta_b*b)
second <- quote(beta_d*d + beta_e*e)
third <- quote(first + second)

I want third to return beta_a*a + beta_b*b + beta_d*d + beta_e*e but instead it returns first + second

Desired result:

third
> beta_a*a + beta_b*b + beta_d*d + beta_e*e

I know that it makes sense that it then returns first + second, but what can I do to get the desired result?

For context, imagine that I need to use this for a specification for an ordered logit model in Apollo. Each first and second type is a variable, and the content is the dummies for that variable. Third then represents a specification. Imagine then I have 10+ variables with 10+ dummies each and I have to make a specification for each combination of variables. It's a lot of manual labour to write out all these utility functions. If I could make the specifications beforehand by condensing first the dummies to variables and then the variables to specifications, it would save me a lot of lines of code and time.


Solution

  • With substitute:

    first <- quote(beta_a*a + beta_b*b)
    second <- quote(beta_d*d + beta_e*e)
    substitute(a + b, list(a = first, b = second))
    #beta_a * a + beta_b * b + (beta_d * d + beta_e * e)