Using `quote()` function in R to generate a multivariable expression

I am attempting to generate a simple multivariable expression in R that is similar to the following:

coef1 * prev1 + coef2 * prev2 + coef3 * prev3

I can do this easily with quote()

quote(coef1 * prev1 + coef2 * prev2 + coef3 * prev3)

which generates the desired call class.

The issue arises when I have multiple coefficients (i.e., multiple coef) to estimate.

I could do this using paste0()

myvec <- 1:3

paste0(paste0("coef",myvec,"*prev",myvec),collapse="+")
#> [1] "coef1*prev1+coef2*prev2+coef3*prev3"

But the issue is that the class of the above is a character. Using quote(), the class is call which can be used to be evaluated.

I also cannot wrap the above in quote because the paste0 function will be included in the expression:

quote(paste0(paste0("coef",myvec,"*prev",myvec),collapse="+"))

will give:

paste0(paste0("coef", myvec, "*prev", myvec), collapse = "+")

when all I want is:

coef1 * prev1 + coef2 * prev2 + coef3 * prev3

Is there any possible way to still generate a call class with multiple variables to estimate without having to explicitly type them all in quote?

Thanks in advance!

  • This expression looks like it should be expressed as a matrix multiplication, i.e., prev %*% coef, where prev is a matrix and coef is a vector (or matrix). What do you need the expression for? There might be better approaches.

    – 




Leave a Comment