From pd@lgd @ending from gm@il@com  Mon Aug  6 10:34:21 2018
From: pd@lgd @ending from gm@il@com (peter dalgaard)
Date: Mon, 6 Aug 2018 10:34:21 +0200
Subject: [Rd] [R] MASS::boxcox "object not found"
In-Reply-To: <6ed54e57.1067.1650a16a89d.Coremail.jszhao@yeah.net>
References: <6ed54e57.1067.1650a16a89d.Coremail.jszhao@yeah.net>
Message-ID: <22AD76FF-FBA8-4202-8193-9410171CD14B@gmail.com>

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 at 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 at 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 at cbs.dk  Priv: PDalgd at gmail.com



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