Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating expressions in R

Tags:

r

expression

I am looking for a way to create an expression that is the product of two given expressions. For example, suppose I have

e1 <- expression(a+b*x)
e2 <- expression(c+d*x)

Now I want to create programatically the expression (e1)*(e2):

expression((a+b*x)*(c+d*x))

Background I am writing a model fitting function. The model has two pieces that are user-defined. I need to be able to "handle" them separately, and then create a combined expression and "handle" it as one model. "Handling" involves taking numeric derivatives, and the deriv function wants expressions as an input.

like image 243
Aniko Avatar asked Feb 02 '23 07:02

Aniko


2 Answers

I don't deal with this too often but something like this seems to be working

e1 <- expression(a + b*x)
e2 <- expression(c + d*x)
substitute(expression(e1*e2), list(e1 = e1[[1]], e2 = e2[[1]]))
# expression((a + b * x) * (c + d * x))
like image 91
Dason Avatar answered Feb 05 '23 12:02

Dason


Try this:

e1 <- quote(a+b*x)   # or expression(*)[[1]]
e2 <- quote(c+d*x)
substitute(e1 * e2, list(e1=e1, e2=e2))
like image 26
Hong Ooi Avatar answered Feb 05 '23 12:02

Hong Ooi