Iago Mosqueira
2007-Jun-26 16:06 UTC
[Rd] Behaviour of mle and environments or calling mle inside a function
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. 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
Prof Brian Ripley
2007-Jun-26 17:41 UTC
[Rd] Behaviour of mle and environments or calling mle inside a function
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