I am trying to combine multiple expressions in R into a single expression. Ideally, I would be able to do something like this:
g <- expression(exp(a[1]*x)/(1 + exp(a[1]*x)))
h <- expression(exp(a[2]*x)/(1 + exp(a[2]*x)))
c <- expression(g * h)
where a
is a given vector of data and x
is the only unknown (and it is the same unknown across all expressions). c
would return
R> c
expression(exp(a[1]*x)/(1 + exp(a[1]*x)) * exp(a[2]*x)/(1 + exp(a[2]*x)))
Right now, when I do this I just get
R> c
expression(g * h)
I want to have an equation
(source: lehrfeld.me)
into which I could plug some vector a
to obtain a function of x
. What am I doing wrong here?
Don't use expressions, use functions. The
From what I can decipher, the following will do what you want
# a function for a vector `x` and single value `a`
func <- function(x,a) { (exp(1)^(a*x)/(1 + exp(1)^(a*x))) }
# a function for a vector `x` and vector length 2 for `a`
foo <- function(x, a){func(x,a[1]) * func(x, a[2])}
# call the function to calculate what you want.
foo(x,a)
And if you want the expression
associated with this so you can plot the text of the equation, the following will work
expr <- expression(exp(1)^(a*x)/(1 + exp(1)^(a*x))
g <- do.call(substitute, list(as.list(expr)[[1]], env= list(a=3)))
h<- do.call(substitute, list(as.list(expr)[[1]], env= list(a=2)))
'%c%' <- function(a,b) bquote(.(a) %*% .(b))
fooExpr <- g %c% h
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