最大化保存为字符串的数学函数

Maximizing mathematical function which is saved as character string

我有以下问题:我正在编写一个函数,它首先构造一个代表数学函数的长字符串,例如“1/(1+exp(-x1+4x3))”。我现在想最大化这个函数,但不幸的是我不能这样做,因为数学函数只保存为字符串而不是 R 函数。我怎么解决这个问题?提前致谢!

I'm writing a function which first constructs a long character string which stands for a mathematical function

不要那样做。我相信有更好的方法。

because the mathematical function is only saved as a character string and not as an R-function

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

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

然后你可以用这个表达式来 "find the maximum" 用你想用的任何方法。

然而,正如 fortune 106 所说:

If the answer is parse() you should usually rethink the question.

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

1) 动态主体 这会将字符串 s 转换为我们可以从 f1 调用的具有 2 个参数的函数 f2根据 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) dynamic body + dynamic args 在上面我们假设我们知道参数,但是如果你想动态创建 body 和 arguments,我们从字符串动态创建 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)