PDA

View Full Version : Using optim function R


asicswrg85
07-18-2010, 10:32 PM
I have a question about how to use the Optim function inside a loop with R. For example given the following coding:

Size=30
Poisson=rpois(Size, lambda=3)
Poisson2=rpois(Size, lambda=4)
Random=rep(10,Size)

poisson.lik=function(mu,y,j,l) {
n=Size
logl=sum(y)*log(mu)*sum(j)-((n*mu)*sum(l))
return(-logl)
}

theta=optim(1,poisson.lik, y=Poisson, j=Poisson2, l=Random, method="BFGS")

If i wanted to turn this into a loop how would I do it. This is the code that I typed, but it is not working:

Size=30
theta=rep(0,Size)
Poisson=rpois(Size, lambda=3)
Poisson2=rpois(Size, lambda=4)
Random=rep(10,Size)


poisson.lik=function(mu,y,j,l) {
n=Size
logl=sum(y)*log(mu)*sum(j)-((n*mu)*sum(l))
return(-logl)
}


for(i in 1:Size) {
optim(1,poisson.lik, y=Poisson[i], j=Poisson2[i], l=Random[i], method="BFGS")
}


Do you know what I am doing wrong or how this should be done?
Thanks