Using optim in R, how would I maximize a function of several variables given a few of them?

3.6k views Asked by At

I have a function of four variables, (c,l,t,a)

I only want to optimize this function over c and l, because a and t are inputs and are used inside the function, sometimes for indexing and stuff. (Which is why I cannot just take the 1st order condition, set equal to zero, etc...).

Any ideas?

Thank you for your help.

EDIT:

Ok so I think the problem might be the way I am using optim sort of. I am going to try something and reframe my q.

1

There are 1 answers

0
Spacedman On BEST ANSWER

You have a function of four parameters:

> foo=function(c,l,t,a){c+10*l+100*t+1000*a}
> foo(1,2,3,4)
[1] 4321

You only want to optimise over two, so make a function of two parameters and call the four-parameter function with the other parameters set:

> f2=function(c,l){foo(c,l,9,8)}
> f2(1,2)
[1] 8921

Now whatever you were doing with foo you do with f2.

If you want you can create a function-generating function that returns functions with the fixed parameters you want you can do this:

> f3gen=function(t,a){force(t);force(a);function(c,l){foo(c,l,t,a)}}

Then you can create a two-parameter function with t and a set to 8 and 9 as before:

> f3=f3gen(8,9)
> f3(1,2)
[1] 9821

And this one gives us a function with them set to 8 and 6:

> f3=f3gen(8,6)
> f3(1,2)
[1] 6821

Now you've got f3 with the values of t and a wrapped up and fixed.

However I thought optim always worked with a single argument vector of parameters, which means, since you've not given us a reproducible example, I've wasted my time explaining this to you.