最小化 R 中的成本

Minimize cost in R

我想最小化下面的函数

cost=function(x){
  events=sum(x==1)
  rev = sum(df$rev[which(x==0)])*0.8

  costcomp1=tail(comp1$cost[which(comp1$Nevents<events)],1)

  costcomp2=tail(comp2$percentuale[which(comp2$k<=rev)],1)*rev+50000

  cost=costcomp1+costcomp2

  return(cost)
}

x 应该是一个二元向量,因为我想为每件商品选择供应商

head(comp2)
        k percentuale
1  800000      0.0500
2 1800000      0.0325
3 88888888888888      0.0200

head(comp1)
       Nevents  cost
1         1500 13000
2         1750 17000
3         2000 21000
4         2500 22500
5         3000 26000
6         3500 29000

我尝试了 optimize(cost,x),x=sample(c(0,1),nrow(df),replace = T) 但它不起作用。它给了我错误 invalid function value in 'optimize'

我想你需要的可能是fminsearch

pracma::fminsearch

你可以试试

pracma::fminsearch(cost,rep(0,nrow(df)))$fmin