简体   繁体   English

nloptr 函数求值时出错

[英]nloptr error in getting the function evaluated

这是我想使用 nloptr 包评估或优化的函数的图像 I am having an issue in running an optimization program in R. I have attached the codes here.我在 R 中运行优化程序时遇到问题。我在这里附上了代码。 This code is for non-linear programming having 8 decision variables(X[j]).此代码用于具有 8 个决策变量 (X[j]) 的非线性规划。 I am trying to maximize the objective function.我正在尝试最大化目标函数。 While running the whole function with nloptr package getting an error in使用 nloptr 包运行整个函数时出现错误

Error in -(for (i in 1:nrow(ldata)) { : 
  invalid argument to unary operator
set.seed(123)
a <- sample(1:6,10,replace = T)
b <- sample(1:3,10,replace= T)
w<- rnorm(10,10,2)
Z<-0.08
Y<-4
D<-2.7
cd<-matrix(0,10,11)
for(i in 1:10){
  cd[i,1]<-a[i]
  cd[i,2]<-w[i]
  cd[i,3]<-cd[i,1]*cd[i,2]
  cd[i,4]<-b[i]
  if (cd[i,4]==1){
    cd[i,5]=max(0,cd[i,3]-23)
  }
  else if (cd[i,4]==2){
    cd[i,5]=max(0,cd[i,3]-28)
  }
  else{
    cd[i,5]=max(0,cd[i,3]-32)
  }
  if (cd[i,4]==1){
    cd[i,6]=max(0,cd[i,1]-2)
  }
  else if (cd[i,4]==2) {
    cd[i,6]=max(0,cd[i,1]-2)
  }
  else {
    cd[i,6]=max(0,cd[i,1]-3)
  }
  cd[i,7]<-cd[i,5]*Y*D
  if (cd[i,6]>=1){
    cd[i,8]=runif(1,120,130)
  }
  else{
    0
  }
  if (cd[i,6]>=2){
    cd[i,9]=runif(1,cd[i,8]+1,140)
  }
  else{
    0
  }
  if (cd[i,6]>=3){
    cd[i,10]=runif(1,cd[i,9]+1,150)
  }
  else{
    0
  }
  if (cd[i,6]>=4){
    cd[i,11]=runif(1,cd[i,10]+1,160)
  }
  else{
    0
  }
};cd
A1<-sum(cd[,7]);A1
ldata<-cd[,-c(1:7)];ldata 
 obj_fn<-function(x){-
    (for(i in 1:nrow(ldata)){
      for(j in 1:4){

    #price[i,j] <- cdata[i,j] * (x[j] + x[j+4]) * Z * D
    ldata[i,j] * as.vector(x[j] + x[j+4]) * Z * D
    }
  })
}

I have no idea if this will work, but try this:我不知道这是否可行,但试试这个:

eg <- expand.grid(i = seq_len(nrow(ldata)), j = 1:4)
obj_fn <- function(x){
  sum(mapply(function(i,j) sum(ldata[i,j] * as.vector(x[j] + x[j+4]) * Z * D),
             eg[[1]], eg[[2]]))
}

Given your sample data and me using an arbitrary x <- 1:8 , I get the following:鉴于您的样本数据和我使用任意x <- 1:8 ,我得到以下信息:

obj_fn(1:8)
# [1] 4640.256

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM