简体   繁体   中英

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. This code is for non-linear programming having 8 decision variables(X[j]). I am trying to maximize the objective function. While running the whole function with nloptr package getting an error in

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:

obj_fn(1:8)
# [1] 4640.256

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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