[R] optim "a log-likelihood function"

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Wed Sep 29 19:41:45 CEST 2004



Christian Schulz wrote:

> Hello,
> 
> i know that i have to use optim, but i'm confused how its
> possible  maximize  the sum over all l[i] and get the optimized
> max(LL), r  and alpha?
> 
> LL <- function(trans,time){
>    for(i in 1:length(trans){
>      l[i] <- log(lgamma(r+trans[i] - 
> gamma(r+1)*(alpha/alpha+t[i]))**r)*(t[i]/alpha+t[i]))**trans[i]
> }
> return(sum(l))
>    }
> 
> i'm confused how i have to set r and alpha 
> and i found no related help in archives?
> 
> ...in Excel it works with solver but only for ~65.000 rows :-)
> 
> #This notation is 1 for trans  and 1  for time instead the Startvalues for r 
> and alpha?
> 

I'm not sure what the above statement means, so I may have 
misinterpretted what you are trying to accomplish.

> optim(c(1,1),-LL)
> 
> many thanks  for an easy example or hint 
> regards,christian
> 

Did you look at the first example in ?optim? There also numerous errors 
in LL: missing parans, time is not used, t is undefined in the function.

LL <- function(x, trans, time) {
   r <- x[1]
   alpha <- x[2]
   ...
   sum(l)
}

optim(c(1, 1), LL, control = list(fnscale = -1),
       trans = trans, time = time)

Some style issues:
1. Break up lines that run too long, especially if you expect others to 
read your code.
2. You don't need an explicit "return" at the end of a function.
3. You should remove the "for" loop in LL and vectorise "l", which 
should be easy.

Hope this is helpful,

--sundar




More information about the R-help mailing list