[R] Arguments to lm() within a function - object not found

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Aug 13 20:33:01 CEST 2008


On Wed, 13 Aug 2008, Pete Berlin wrote:

> Hi all,
>
> I'm having some difficulty passing arguments into lm() from within a
> function, and I was hoping someone wiser in the ways of R could tell me
> what I'm doing wrong. I have the following:
>
> lmwrap <- function(...) {
>
>  wts <- somefunction()
>  print(wts) # This works, wts has the values I expect
>  fit <- lm(weights=wts,...)
>
>  return(fit)
> }
>
> If I call my function lmwrap, I get the the following error:
>
>> lmwrap(a~b)
> Error in eval(expr, envir, enclos) : object "wts" not found

Correct.  The help (?lm) says

      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'.


>
> A traceback gives me the following:
>
> 8: eval(expr, envir, enclos)
> 7: eval(extras, data, env)
> 6: model.frame.default(formula = ..1, weights = wts, drop.unused.levels =
> TRUE)
> 5: model.frame(formula = ..1, weights = wts, drop.unused.levels = TRUE)
> 4: eval(expr, envir, enclos)
> 3: eval(mf, parent.frame())
> 2: lm(weights = wts, ...)
> 1: wraplm(a ~ b)
>
> It seems like whatever environment lm is trying to eval wts in doesn't
> have it defined.
>
> Could anyone tell me what I'm doing wrong?
>
> As a sidenote, I do have a workaround, but this strikes me as really the
> wrong thing to do. I replace the call to lm with:
> eval(substitute(lm(weights = dummy,...),list(dummy=wts)))
> which works.

It's one workaround, but working with the scoping rules is better.  Hint: 
use the 'data' argument to lm.


-- 
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



More information about the R-help mailing list