[R] mle() and with()

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Jan 10 22:41:39 CET 2005


Ben Bolker <bolker at zoo.ufl.edu> writes:

>    I'm trying to figure out the best way of fitting the same negative
> log-likelihood function to more than one set of data, using mle() from
> the stats4 package.

It's not the same likelihood function if the data differ, since
likelihood functions are  functions of the parameters only. The design
of mle() & friends is so as to reinforce that idea.
 
> Here's what I would have thought would work:
> 
> --------------
> library(stats4)
> 
> ## simulate values
> r = rnorm(1000,mean=2)
> 
> ## very basic neg. log likelihood function
> mll <- function(mu,logsigma) {
>    -sum(dnorm(r,mean=mu,sd=exp(logsigma),log=TRUE))
> }
> 
> 
> mle(minuslogl=mll,start=list(mu=1,logsigma=0))
> 
> r2 = rnorm(1000,mean=3) ## second "data set"
> with(list(r=r2),
>       mle(minuslogl=mll,start=list(mu=1,logsigma=0))
>     )
> -------------
> 
> but this doesn't work -- it fits to the original data set, not the new
> one --- presumably because mll() picks up its definition of r when it
> is *defined* -- so using with() at this point doesn't help.
> 
>    If I rm(r) then I get an 'Object "r" not found' error.
> 
> 
> I can do something like the following, defining the negative
> log-likelihood function within the mle() call ...
> 
> lf = function(data) {
>    mle(minuslogl=function(mu,logsigma) {
>      -sum(dnorm(data,mean=mu,sd=exp(logsigma),log=TRUE))
>    },start=list(mu=1,logsigma=0))
> }
> 
> lf(r)
> lf(r2)
> 
> -------
> 
>   ... and in this case there's no point using with().
>   can someone help me understand this behavior and to find a clean way
> to use mle() on a predefined likelihood function that allows
> substitution of an arbitrary data set?

I'd do 

mll <- function(data) function(mu,logsigma) 
    -sum(dnorm(data,mean=mu,sd=exp(logsigma),log=TRUE))

fit <- mle(minuslogl = mll(r), start = list(mu=1, logsigma=0))
fit2 <- mle(minuslogl = mll(r2), start = list(mu=1, logsigma=0))

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list