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

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Thu Sep 30 03:21:17 CEST 2004



Zhen Pang wrote:

> 
> I also use optim, however, for my case, can you show some light on 
> avoiding the loop?
> 
> There are around 200 sets of (i,j,k) where i<=j<=k. 3 situations exist 
> whether "=" hold, I list one for example,
> 
>                      l<-i:(k-j+i)
>                      s<-rep(0,k)
>                      s[l]<-choose(j,i)*choose((k-j),(l-i))/choose(k,l)
>                      ss<-sum(s*x0)
> 
> then sum all the log(ss) is my log-liklihood function.
> 
> One loop from 1 to 200 is inevitable. I have tried to use vector, 
> however, I only can simply to this situation.  Thanks.
> 
> Regards,
> 
> Zhen
> 

Zhen,
   Your question doesn't really have much to do with optim, so I changed 
the subject line.

It's difficult to see what you're trying to accomplish without a 
complete example. Could you post one? Also, for loops are necessarily bad.

One thing to note is that you're better off using lchoose in the above 
code. I.e.

log.s <- lchoose(j, i) + lchoose(k - j, l - i) - lchoose(k, l)
s[l] <- exp(log.s)

--sundar




More information about the R-help mailing list