Reputation: 1
I don't get how to use the optim() function. I tried something simple (at least i thought so). Here is the code:
w<-c(0.5,0.5)
A<-runif(100)
B<-runif(100)
c<-function(w,A,B) sqrt(w[1]*A + w[2]*B)
optim(w,c)
Error in w[1]*A:'A' is missing
I have seen various questions of this type but I still don't know what is wrong. What am I missing here?
Upvotes: 0
Views: 62
Reputation: 311
There are two separate things to look at in the code above.
First, in the optim
function you need to pass in the other arguments to c
(as part of the ...
argument to optim
:
optim(w, c, A = A, B = B)
But that still won't run because the function your trying to optimise returns a vector (optim tries to minimise the value of the function by default).
Because you say it's an example, it's not clear what to do with the function c
but just to show something that should work, you could try the sum of the squared differences between A & B:
c <- function(w, A, B) sum((w[1] * A - w[2] * B)^2)
optim(w, c, A = A, B = B)
Upvotes: 1