Re: [Rd] Behaviour of mle and environments or calling mle inside a function

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Tue, 26 Jun 2007 18:41:55 +0100 (BST)

On Tue, 26 Jun 2007, Iago Mosqueira wrote:

> Dear all,
>
> I would appreciate some help understanding the following behaviour
> when stats4::mle is called inside a function. mle seems to look for
> its arguments in R_GlobalEnv and not the environment from which it is
> called.

It is your function lkhd() that is doing the looking, and lexical scoping means that it should be looking in .GlobalEnv (sic), since that is where you defined it. Try a traceback:

> traceback()

10: log(rec)
9: dnorm(log(rec), log(alpha * ssb/(beta + ssb)), sqrt(sigma), TRUE) 8: sum(dnorm(log(rec), log(alpha * ssb/(beta + ssb)), sqrt(sigma),

        TRUE))

7: minuslogl(alpha = 1, beta = 0.1, sigma = 0.1)
6: do.call("minuslogl", l)
5: fn(par, ...)
4: function (par)

    fn(par, ...)(c(1, 0.1, 0.1))

3: optim(start, f, method = method, hessian = TRUE, ...)
2: mle(x$lkhd)
1: foo(object)

I am afraid I have no idea why you thought that your function would look in the body of foo().

>
>
> library(stats4)
>
> lkhd <- function(alpha=1, beta=0.1, sigma=0.1)
> - sum(dnorm(log(rec), log(alpha*ssb/(beta+ssb)), sqrt(sigma), TRUE))
>
> object <- list(lkhd=lkhd, rec=1:10, ssb=1:10)
>
> foo <- function(x)
> {
> rec <- x$rec
> ssb <- x$ssb
>
> mle(x$lkhd)
> }
>
> foo(object)
>
>
> This fails with
>
> Error in log(rec) : object "rec" not found
>
>
> rec <- object$rec
> ssb <- object$ssb
>
> foo(object)
>
> and this works.
>
> Using R version 2.5.0 (2007-04-23), on Linux (Ubuntu) 2.6.17
>
> Many thanks,
>
>
> Iago Mosqueira
>
> ______________________________________________
> R-devel_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>

-- 
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

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Tue 26 Jun 2007 - 17:46:46 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 26 Jun 2007 - 19:35:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.