Skip to content
Prev 29040 / 63421 Next

scoping problem when calling lm(precomputed formula, weights) from function (PR#11540)

On 5/30/2008 11:40 AM, rocket at google.com wrote:
No, in your use of it.
... incorrectly.
If this were simply

Formula <- y ~ x

it would work, because then the formula would get the evaluation 
environment attached.  I assume your real case builds up a formula in 
text and then parses it, in which case you'll have to evaluate the 
formula to get the environment set:

 > g
function (k)
{
     w <- data$z^k
     Formula <- eval(parse(text = "y ~ x"))
     coef(lm(Formula, data = data, weights = w))
}
 > g(2)
(Intercept)           x
   0.7777419  -0.7023185

In more complicated cases, you may need to explicitly set the 
environment of the constructed formula, using e.g.

environment(Formula) <- environment()

Duncan Murdoch