Vectorising and loop (was Re: [R] optim "alog-likelihood function")

Zhen Pang nusbj at hotmail.com
Thu Sep 30 09:06:24 CEST 2004


ok. You just simulate a 200 by 3 matrix z, all positive integers. The first 
column is i, the second column is j, and the third column is in fact the 
frequency of (i,j) combination, you can set the third column to be 1 for 
simplification.  Notice that i<j, and k=max of the second column. theta is a 
k dimension vector I want to maximize over.

ll <- function(theta)
   {t<-0
    for (ii in 1:k)
       {t<-t+exp(theta[ii])}
    lll<-0
    x00<-1/(1+t)
    x0<-x00*exp(theta)
for (m in 1:200)
    {i<-z[m,1]
     j<-z[m,2]
     a<-z[m,3]
     l<-i:(k-j+i)
     s<-rep(0,k)
     s[l]<-choose(j,i)*choose((k-j),(l-i))/choose(k,l) # we only define some
of s to be non-zero, since dim(l) might be smaller than dim(s)
     ss<-sum(s*x0)  # ss is a weighted sum of x0
      lll<-lll+a*log(ss)
     }
-lll
# the negative sign is to find the maximum of the log-likelihood function. 
It can be omitted if we use the finscale option in optim.
}

Then I need to optim(b0,ll,hessian=T), where b0 is k dimension starting 
value.

I have tried to use eval() and modify my function, it seems to be able to 
remove the m loop, however, optim() can not recognize it. So my main concern 
is to avoid the loop and optim() can works for my function. Thanks.

Regards,

Zhen




More information about the R-help mailing list