我已经将多项式模型拟合到某些数据中,我想从该模型中提取公式以找到它的最大值。我可以从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
有什么想法吗?
答案 0 :(得分:3)
#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