结合R中的表达式 [英] Combining expressions in R

查看:97
本文介绍了结合R中的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将R中的多个表达式组合为一个表达式.理想情况下,我可以执行以下操作:

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)

其中,a是给定的数据向量,而x是唯一的未知数(并且在所有表达式中都是相同的未知数). c将返回

R> c
expression(exp(a[1]*x)/(1 + exp(a[1]*x)) * exp(a[2]*x)/(1 + exp(a[2]*x)))

现在,当我这样做时,我会得到

R> c
expression(g * h)

我想要一个方程式


(来源: lehrfeld.me )

我可以在其中插入一些向量a以获得x的功能.我在这里做什么错了?

解决方案

不要使用表达式,请使用函数.

根据我的理解,以下将满足您的要求

# 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)

如果您希望将expression与之关联,则可以绘制等式的文本,那么下面的方法将起作用

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

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

这篇关于结合R中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆