Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write mathematical equation in R with constants coming from variables?

Tags:

r

In R- statistics, suppose I have

a <- 5

b <- 3

Now I want to write a mathematical equation using expression function as below

exp <- expression(a * e ^ (b * x))

But I want the values of a and b in the equation instead of the letters,

i.e. I want it to show 5 e^3x.

How do I do that?

The reason is that I wouldn't know the values a and b in advance and these are coming from fitting an exponential curve, so I cannot use expression(5 * e ^ (3 * x)).

like image 651
Ravaging Care Avatar asked Aug 01 '14 12:08

Ravaging Care


2 Answers

Try this:

subst <- function(e, ...) do.call(substitute, list(e[[1]], list(...)))
exp <- expression(a * e^(b * x))
subst(exp, a = 1, b = 5)
## 1 * e^(5 * x)

Note that while it might appear that the simpler

substitute(expression(a * e^(b * x)), list(a = 1, b = 5))

works, you cannot simply replace expression(a * e^(b * x)) with a variable so it only works if your application allows you to hard code the expression.

like image 154
G. Grothendieck Avatar answered Nov 03 '22 20:11

G. Grothendieck


You can use the substitute command

a <- 5
b <- 3
substitute(expression(a * e^(b * x)), list(a=a, b=b))
# expression(5 * e^(3 * x))

or just

substitute(a * e^(b * x), list(a=a, b=b))
# 5 * e^(3 * x)
like image 45
MrFlick Avatar answered Nov 03 '22 19:11

MrFlick