Paul Cuckoo - 7 months ago 47

R Question

I have a function in R that I wish to maximise subject to some simple constraints in

`optim`

`constrOptim`

`ci`

`ui`

My function is:

`negexpKPI <- function(alpha,beta,spend){`

-sum(alpha*(1-exp(-spend/beta)))

}

where

`alpha`

`beta`

`spend`

`c(sp1,sp2,...,sp6)`

`negexpKPI`

`spend`

1) Min and max for each

`sp1,sp2,...,sp6`

`0 < sp1 < 1000000`

`5000 < sp2 < 1000000`

...

2) A total sum:

`sum(spend)=90000000`

3) A sum for some individual components:

`sum(sp1,sp2)=5000000`

Any help please? Open to any other methods that would work but would prefer base R if possible.

Answer

According to `?constrOptim`

:

```
The feasible region is defined by ‘ui %*% theta - ci >= 0’. The
starting value must be in the interior of the feasible region, but
the minimum may be on the boundary.
```

So it is just a matter of rewriting your constraints in matrix format. Note, an identity constraint is just two inequality constraints.

Now we can define in R:

```
## define by column
ui = matrix(c(1,-1,0,0,1,-1,1,-1,
0,0,1,-1,1,-1,1,-1,
0,0,0,0,0,0,1,-1,
0,0,0,0,0,0,1,-1,
0,0,0,0,0,0,1,-1,
0,0,0,0,0,0,1,-1), ncol = 6)
ci = c(0, -1000000, 5000, -1000000, 5000000, 90000000, -90000000)
```

Source (Stackoverflow)