[Rd] [R] MASS::boxcox "object not found"

peter dalgaard pd@lgd @ending from gm@il@com
Mon Aug 6 10:34:21 CEST 2018


Hmm, this looks like a buglet/infelicity in update.lm rather than MASS::boxcox per se. Moving to R-devel.

I think the story is that update.lm eventually does

        eval(call, parent.frame())

where the call is extracted from the lm object, but call$formula is unevaluated, and does not contain environment information like formula(obj) would do. Then when the call is evaluated and parent.frame() differs from that of the original call, trouble ensues.

A workaround not involving <<- seems to be 

  ...
  obj <- lm(vec ~ 1)
  obj$call$formula <- formula(obj)
  lam <- boxcox(obj)
  ...

I'm not sure whether this is actually fixable. It is the kind of thing where you tend to discover that someone, somewhere has actually been relying on current behaviour...

-pd

> On 5 Aug 2018, at 14:36 , Jinsong Zhao <jszhao using yeah.net> wrote:
> 
> Hi there,
> 
> I wrote a function that wraps MASS::boxcox as:
> 
> bc <- function(vec) {
>   lam <- boxcox(lm(vec ~ 1))
>   lam <- lam$x[which.max(lam$y)]
>   (vec^lam - 1)/lam
> }
> 
> When I invoke it as:
> 
>> x <- runif(20)
>> bc(x)
> Error in eval(predvars, data, env) : object 'vec' not found
> 
> I have googled, and rewrote the above function as:
> 
> bc <- function(vec) {
>   dat <<- data.frame(vec = vec)
>   lam <- boxcox(lm(vec ~ 1, dat))
>   lam <- lam$x[which.max(lam$y)]
>   rm(dat, envir = .GlobalEnv)
>   (vec^lam - 1)/lam
> }
> 
> It works. But, I am wondering why MASS::boxcox have to wrap in such way that have to use the data in .GlobalEnv.
> 
> Best,
> Jinsong
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes using cbs.dk  Priv: PDalgd using gmail.com



More information about the R-devel mailing list