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

标签 r

我已经为一些数据拟合了一个多项式模型,我想从该模型中提取公式以找到它的最大值。我能够从 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/

相关文章:

r - ggplot2 geom_line() 特定值之间的箭头方向

r - 将数据表导出到 R 中的 Google Maps KML

r - 使用带有 scale_y_log10 的 geom_histogram 时如何抑制零

R reshape 2 'Aggregation function missing: defaulting to length'

替换列中匹配的值

r - dplyr 总结的变量结果,取决于输出变量命名

r - 如何使用st_join()与sf包进行空间连接

r - 如何在 ggplot2 中不间断地添加轴标签?

r - 16 位以上整数的计算

r - 改变 dplyr 中的 tibble 列以保存标签文本而不是值