0

I'd like to minimize the following function

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 should be a binary vector, because for every item I want to choose the supplier to buy from

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

I tried optimize(cost,x),x=sample(c(0,1),nrow(df),replace = T) but it doesn't work. It gives me the error invalid function value in 'optimize'

  • How about `optim(cost, x)`? This post looks similar to what you want: https://stackoverflow.com/questions/17013612/how-to-minimize-a-function-over-one-input-parameter-in-r. – Edward Feb 17 '20 at 10:42
  • ```Error in optim(cost, x) : cannot coerce type 'closure' to vector of type 'double' Inoltre: Warning message: In optim(cost, x) : one-dimensional optimization by Nelder-Mead is unreliable: use "Brent" or optimize() directly``` – Riccardo Tornaghi Feb 17 '20 at 10:47

1 Answers1

1

I think what you need might be fminsearch

pracma::fminsearch

and you can try

pracma::fminsearch(cost,rep(0,nrow(df)))$fmin
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81