簡體   English   中英

R將字符串公式轉換為函數

[英]R convert a string formula to a function

我已經將多項式模型擬合到一些數據,並且我想從該模型中提取公式以找到其最大值。 我可以從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM