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)).
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With