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

Pete Berlin
Wed, 13 Aug 2008 16:05:56 -0000

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

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.

Thanks
Pete