【问题标题】:Error in f2(x, ...) : could not find function "n": I am not using any function "n" nor defined itf2(x, ...) 中的错误:找不到函数“n”:我没有使用任何函数“n”,也没有定义它
【发布时间】:2017-04-06 22:02:43
【问题描述】:

我正在使用“nloptr”包解决 R 中的优化问题。

 N_h <- c(39552, 38347, 43969, 36942, 41760)
 s_h1 <- c(4.6, 3.4, 3.3, 2.8, 3.7)
 s_h2 <- c(11.7, 9.8, 7.0, 6.5, 9.8)
 s_h3 <- c(332, 357, 246, 173, 279)

 N <- sum(N_h)
 d_h <- c(N_h/N)
 d1 <- c(s_h1[1]*(d_h[1])^2, s_h1[2]*(d_h[2])^2, s_h1[3]*(d_h[3])^2,s_h1[4]*(d_h[4])^2, s_h1[4]*(d_h[5])^2)
 d2 <- c(s_h2[1]*(d_h[1])^2, s_h2[2]*(d_h[2])^2, s_h2[3]*(d_h[3])^2,s_h2[4]*(d_h[4])^2, s_h2[4]*(d_h[5])^2)
 d3 <- c(s_h3[1]*(d_h[1])^2, s_h3[2]*(d_h[2])^2, s_h3[3]*(d_h[3])^2, s_h3[4]*(d_h[4])^2, s_h3[4]*(d_h[5])^2)
 library('nloptr')

 #Objective function
 f0 <- function(n, d1=d1, d2=d2, d3=d3){
  return(n[6])  
 }

#Constraints
g0 <- function(n, d1, d2, d3){
return(c(
(n[1]+n[2]+n[3]+n[4]-1065), 
(w1*(d1[1]/n[1]+d1[2]/n[2]+d1[3]/n[3]+d1[4]/n[4]+d1[5]/n[5]-n(6))+w2*(d2[1]/n[1]+d2[2]/n[2]+d2[3]/n[3]+d2[4]/n[4]+d2[5]/n[5]-n(6))
+w3*(d3[1]/n[1]+d3[2]/n[2]+d3[3]/n[3]+d3[4]/n[4]+d3[5]/n[5]-n(6))
)) )
}

 #Initialization
 n<- c(2,2,2,2,2,100)
 w1=0.333
 w2=0.333
 w3=0.333
 Rob1 <- cobyla(n, f0, hin = g0, nl.info = TRUE, control = list(xtol_rel = 1e-8, maxeval = 4000), d1=d1, d2=d2, d3=d3)

显示以下错误

   Error in f2(x, ...) : could not find function "n"

我没有定义任何函数“n”,我也不需要它。

你能帮我看看我哪里做错了吗?

谢谢

【问题讨论】:

    标签: r optimization


    【解决方案1】:

    看看你的代码,你有n(6)而不是n[6]。这使得n 看起来像一个函数而不是一个向量。这只是一个错字。

    【讨论】:

    • 我只是在写同样的东西。因为n是一个向量,所以元素应该被称为n[6]。用n(6) 理解n 是一个函数,6 是它的参数。
    • 哦...非常感谢。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-06-14
    • 2022-08-08
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2021-04-15
    • 2014-09-29
    相关资源
    最近更新 更多