Maximizing mathematical function which is saved as character string

时间:2016-12-28 11:41:26

标签: r function character maximize

I have the following problem: I'm writing a function which first constructs a long character string which stands for a mathematical function, e.g. "1/(1+exp(-x1+4x3))". I now want to maximize this function, but unfortunately I cannot do so because the mathematical function is only saved as a character string and not as an R-function. How can I solve this problem? Thanks in advance!

2 个答案:

答案 0 :(得分:1)

如果我们提前知道参数是什么,则(1)将是首选,因为它更简单(4行代码)但如果我们不这样做(2)也涵盖生成它们(8行代码) )。

1)动态正文这会将字符串s转换为2个参数的函数f2,我们可以根据需要从f1调用一个参数optim

s <- "1/(1+exp(-x1+4*x3))" # test input

f1 <- function(x) do.call("f2", as.list(x))  # f1 calls f2

f2 <- function(x1, x3) {}
body(f2) <- parse(text = s)

optim(c(0, 0), f1, control = list(fnscale = -1))

2)动态body +动态args 在上面我们从字符串动态创建了主体,假设我们知道了参数,但是如果你想动态创建body和参数,那么试试这个。这里f2不再必须有2个参数,但有nv个参数,它们是从输入s派生的。

s <- "1/(1+exp(-x1+4*x3))" # test input - same as above

f1 <- function(x) do.call("f2", as.list(x))  # function on one argument - same as above

# f2 has nv arguments
f2 <- function() {}
p <- parse(text = s)
v <- all.vars(p) # character string of variable names used for arguments
nv <- length(v)
formals(f2) <- setNames(rep(alist(x=), nv), v)
body(f2) <- p

optim(numeric(nv), f1, control = list(fnscale = -1)) # first arg different from (1)

答案 1 :(得分:0)

  

我正在写一个函数,它首先构造一个代表数学函数的长字符串

不要这样做。我确信有更好的方法。

  

因为数学函数只保存为字符串而不是R函数

您需要解析字符串(在使其成为有效的R语法之后):

expr <- parse(text = gsub("((?<=\\d)[[:alpha:]])", "\\*\\1","1/(1+exp(-x1+4x3))", perl = TRUE))

然后你可以使用这个表达式来找到最大值&#34;用你想用的任何方法。

然而,正如fortune 106所说:

  

如果答案是解析(),你通常应该重新考虑这个问题。