[R] environment of lm

William Dunlap wdunlap at tibco.com
Sun Jun 23 22:25:45 CEST 2013

Your web site had
  WeightsBreaks <- function(){
    someData <- data.frame(x = rnorm(20, 5, 1),y =  1:20 + runif(20),z =  70:51, weight = 0.05)
    print( ls())
    ModObject <- lm('x~y + z', data = someData, weights = someData$weight)
and I got the result
  > print(WeightsBreaks())
  [1] "someData"
  Error in eval(expr, envir, enclos) : object 'someData' not found
When I remove the quotes around the formula string, from
  lm('x~y + z',...)
  lm(x~y + z, ...)
then I get
  > print(WeightsBreaks())
  [1] "someData"
  lm(formula = x ~ y + z, data = someData, weights = someData$weight)
  (Intercept)            y            z  
      47.7740      -0.5689      -0.6028  

The object 'x ~ y + z' is a character string, not a formula.  It gets converted into a formula by as.formula by lm() or perhaps by something that lm() calls.  The 'environment of a formula' is the environment in which the formula is created (unless you explicitly change it) so this explains why lm() could not find your stuff.

If you are are constructing your formula string using something like paste(), convert it yourself to a formula by calling as.formula explicitly from the environment where the objects it uses are.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Dave Mitchell
> Sent: Sunday, June 23, 2013 9:32 AM
> To: r-help at r-project.org
> Subject: [R] environment of lm
> Hello,
> I'm running into what I believe is a scoping issue having to do with the
> environment in which the weights argument is evaluated in lm.  From the lm
> documentation "All of weights, subset and offset are evaluated in the same
> way as variables in formula, that is first in data and then in the
> environment of formula.".  In the code at http://pastebin.com/kqzxxicp I
> have 3 functions identical to each other except for
> WeightsBreaks adds "weights = someData$weight"
> and
> Works uses the <<- assignment operator for someData.
> My interpretation of the quoted documentation above is that lm looks at the
> data argument to find weights, subset and offset and then to the
> environment in which the formula argument lives.  Am I missing something?
> Why is it that lm only sees weights (here someData$weight) when it's in the
> global environment, yet lm sees data (someData in this case) regardless of
> whether it's in the global environment or just local to the function?
> Thanks for your time.
> Dave
> 	[[alternative HTML version deleted]]
> ______________________________________________
> R-help at r-project.org mailing list
> 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.

More information about the R-help mailing list