[R] wrapping mle()

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Dec 30 08:41:48 CET 2006


On Fri, 29 Dec 2006, Sebastian P. Luque wrote:

> Hi,
>
> How can we set the environment for the minuslog function in mle()?  The
> call in this code fails because the "ll" function cannot find the object
> 'y'.  Modifying from the example in ?mle:
>
>
> library(stats4)
> ll <- function(ymax=15, xhalf=6) {
>    -sum(stats::dpois(y, lambda=ymax/(1+x/xhalf), log=TRUE))
> }
> fit.mle <- function(FUN, x, y) {
>    loglik.fun <- match.fun(FUN)
>    mle(loglik.fun, method="L-BFGS-B", lower=c(0, 0))
> }
> fit.mle("ll", x=0:10, y=c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8))
>
>
> How should "fit.mle" be constructed so that "ll" works on the appropriate
> environment?  Thanks in advance for any advice on this.

You need to set the environment of ll to that containing your data 
objects.  This would happen automatically if you defined ll in the 
function fit.mle.  A brutal solution would be

fit.mle <- function(FUN, x, y) {
    loglik.fun <- match.fun(FUN)
    environment(loglik.fun) <- sys.frame(sys.nframe())
    mle(loglik.fun, method="L-BFGS-B", lower=c(0, 0))
}

but of course that would remove the previous environment from the scope, 
so you may need something like

    env <- sys.frame(sys.nframe())
    parent.env(env) <- environment(ll)
    environment(loglik.fun) <- env


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list