Mariam Z.
Mariam Z.

Reputation: 21

ContrOptim Function- Error in Argument

I'm trying to replicate the Excel Solver in R- which is basically a constraint optimization problem

I'm trying to minimize the cost per action which is total spend/ total actions which equals to the below function with a few constraints.

CPA function:

(a+b+c+d)/((consta+(Baln(a)))+ (constb+(Bbln(b)))+(constc+(Bcln(c)))+(constd+(Bdln(d)))

where the unknown variables are a,b,c,d and const* stands for constant from a regressions and B* stand for coefficient from a regression (so they are values that I have).

Here is the simplified filled in function that I'm trying to minimize:

(a+b+c+d)/ (((69.31*ln(a))+(14.885*ln(b))+(21.089*ln(c))+(9.934*ln(d))-(852.93))

Constraints:

a+b+c+d>=0    
a+b+c+d<=130000(total spend)
a<=119000 (maxa)
a>=272.56(mina)
b<=11000(maxb)
b>=2.04(minb)
c<=2900(maxc)
c>=408.16(minc)
d<=136800(maxd)
d>=55.02(mind)

I'm doing this using the constraints optimization function. My code is below:

g<-function(a,b,c,d) { (a+b+c+d)/((consta+(Balog(a)))+ (constb+(Bblog(b)))+ (constc+(Bclog(c)))+ (constd+(Bdlog(d)))) }

gb<-function(a) g(a[1], a[2], a[3],a[4])

A<-matrix(c(1,0,0,0,-1,0,0,0,0,1,0,0,0,-1,0,0,0,0,1,0,0,0,-1,0,0,0,0,1,0,0,0,-1,-1,-1,-1,-1,1,1,1,1),4,10)

B<- c(mina, -maxa, minb, -maxb, minc, -maxc, mind, -maxd,-totalspend, 0)

constrOptim(c(273,6,409,56),g,gb,A,B)

When I run the optimization function, it states that something is wrong with my arguments (Error in ui %*% theta : non-conformable arguments). I think it is the gradient of the function that is coded wrong but I'm not sure. Any help is appreciated.

Upvotes: 0

Views: 227

Answers (1)

Emmanuel Hamel
Emmanuel Hamel

Reputation: 2213

You can consider the following approach

library(DEoptim)

fn_Opt <- function(param)
{
  a <- param[1]
  b <- param[2]
  c <- param[3]
  d <- param[4]
  
  bool_Cond <- a + b + c + d <= 130000
  
  if(bool_Cond == FALSE)
  {
    return(10 ^ 30)
    
  }else
  {
    val <- (a + b + c + d) / (((69.31 * log(a)) + (14.885 * log(b)) + (21.089 * log(c)) + (9.934 * log(d)) - (852.93)))
    return(val)
  }
}

obj_DEoptim <- DEoptim(fn = fn_Opt, lower = c(272.56, 2.04, 408.16, 55.02),
                       upper = c(119000, 11000, 2900, 136800),
                       control = list(itermax = 10000))

Upvotes: 0

Related Questions