Skip to content
Prev 325812 / 398506 Next

environment of lm

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',...)
to
  lm(x~y + z, ...)
then I get
  > print(WeightsBreaks())
  [1] "someData"
  
  Call:
  lm(formula = x ~ y + z, data = someData, weights = someData$weight)
  
  Coefficients:
  (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