Optim inside function:承诺已经在评估中

时间:2017-03-19 21:44:29

标签: r function optimization

关于错误消息“承诺已经评估”和范围界定的几个主题。然而,这似乎并非如此。我试图在其他函数中使用optim。为了重现相同的错误,我把一个最小的例子放在下面。有没有办法避免这种情况?

set.seed(123)

df_ss = data.frame(var1 = rnorm(100), 
                   var2 = rnorm(100), 
                   var3 = rnorm(100), 
                   var4 = rnorm(100))

test <- function(df_ss = df_ss, degree = 3, raw = TRUE, ...){
  # objective function
  objective <- function(beta, df_ss = df_ss) {
    op2 <- lm(formula = I(var1 - beta*var2) ~ poly(I(var3 - beta*var2), degree = degree), data = df_ss)
    return (sum(residuals(op2)^2))
  }

  ss_reg <- optim(1, fn = objective , method ="Brent",lower =-1, upper =1)
}


test()
Error in model.frame.default(formula = I(var1 - beta * var2) ~ poly(I(var3 -  : promise already under evaluation: recursive default argument reference or earlier problems?

1 个答案:

答案 0 :(得分:2)

以下作品。避免做df_ss = df_ss

test <- function(dat = df_ss, degree = 3, raw = TRUE, ...){
  # objective function
  objective <- function(beta) {
    op2 <- lm(formula = I(var1 - beta*var2) ~ poly(I(var3 - beta*var2), degree = degree, raw = raw), data = dat)
    return (sum(residuals(op2)^2))
  }

  ss_reg <- optim(1, fn = objective , method ="Brent",lower =-1, upper =1)
}

result <- test()
result
# par
# [1] -0.03866607
#
# value
# [1] 80.22191