gpt4 book ai didi

R将字符串公式转换为函数

转载 作者:行者123 更新时间:2023-12-04 00:30:23 24 4
gpt4 key购买 nike

我已经为一些数据拟合了一个多项式模型,我想从该模型中提取公式以找到它的最大值。我能够从 lm 对象中提取一个公式作为字符串,但是我无法从该字符串创建一个将与 optimize 函数一起使用的新函数。

## function for generating data
f1 = function(x) 1 + x^2 - x^3

## random variable from normal distribution
yran = rnorm(500, 1, .025)

## create data by fitting function f to x points times the random variable
dt = data.frame(x = seq(.01, 1, .01) * yran,
y = f1(seq(.01, 1, .01))*yran)

## sort data frame by x
dt = dt[order(dt$x, decreasing = FALSE), ]

## plot the generated data
plot(dt, ylim = c(.9, 1.24))

## create a polynomial model
fit3 = lm(y ~ poly(x, 3), dt)

## plot the models over the data
lines(x = dt$x, predict(fit3, data.frame(x = dt$x)), col = "red", lwd = 2)

## fit the original model for comparison
lines(x = dt$x, f1(dt$x), lwd = 2, lty = 2)

我创建的函数只是提取系数并将公式粘贴在一起。我的挑战是能够从模型字符串创建一个函数。

  ext.mdl = function(lm) {

int = paste(lm$coefficients[[1]][[1]])
coef = paste(lm$coefficients[2:length(lm[[1]])])

out = as.character()

for (i in 1:length(coef)) {
out = paste(out, coef[i], "*x^", i, " + ", sep = "")

}

out = gsub('.{3}$', '', out)
out = paste(int, '+', out)

return(out)
}

> ext.mdl(fit3)
[1] "1.08475891509144 + 0.599668223720749*x^1
> + -0.822484955777266*x^2 + -0.377150292824362*x^3"

理想情况下,我希望能够为从 ext.mdl() 中提取的任何内容分配一个新函数,这样我就可以使用 optimize() 找到最大值在函数中。最终,我需要能够通过“function(x) [model string]”进行优化。

> optimize(function(x) 1.08475891509144 + 0.599668223720749*x^1 
+ + -0.822484955777266*x^2 + -0.377150292824362*x^3,
+ interval = c(0,1), maximum = TRUE)
$maximum
[1] 0.3018792

$objective
[1] 1.180457

有什么想法吗?

最佳答案

#parse the string and then evaluate the expression
optimize(function(x) eval(parse(text=ext.mdl(fit3))),
interval = c(0,1), maximum = TRUE)

$maximum
[1] 0.3007581

$objective
[1] 1.179404

关于R将字符串公式转换为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28908494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com