Constraint Optimization using R

#1
Hi,

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+(Ba*ln(a)))+ (constb+(Bb*ln(b)))+(constc+(Bc*ln(c)))+(constd+(Bd*ln(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+(Ba*log(a)))+ (constb+(Bb*log(b)))+ (constc+(Bc*log(c)))+ (constd+(Bd*log(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)




This is the constraint matrix and vector that I used to derive A and B above:


A B

1 0 0 0 (a (272.56
-1 0 0 0 b -119000
0 1 0 0 c 2.04
0 -1 0 0 d) 11000
0 0 1 0 408.16
0 0 -1 0 2900
0 0 0 1 55.02
0 0 0 -1 136800
-1 -1 -1 -1 -130000
1 1 1 1 0)



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.

Thank you,