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

Pete Berlin pete at yesbutno.com
Wed Aug 13 21:54:00 CEST 2008


Thanks very much for the quick reply. I had looked at the help for lm,
but I clearly skimmed over the critical part explaining where weights is
evaluated.

Thanks,
Pete



On 13/8/2008, Prof Brian Ripley wrote:

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



More information about the R-help mailing list