From murdoch@dunc@n @end|ng |rom gm@||@com  Mon Aug 10 20:34:20 2020
From: murdoch@dunc@n @end|ng |rom gm@||@com (Duncan Murdoch)
Date: Mon, 10 Aug 2020 14:34:20 -0400
Subject: [Rd] lm() takes weights from formula environment
In-Reply-To: <CC3F936D-DA0C-4681-A5F0-1A2C790147D3@win-vector.com>
References: <C57EF170-CC1D-426A-A659-3EA8B198EBC6@win-vector.com>
 <509f3b0d-d531-20cd-ea34-bd340d5be3b0@gmail.com>
 <CC3F936D-DA0C-4681-A5F0-1A2C790147D3@win-vector.com>
Message-ID: <f299efeb-503e-dab6-f119-fe087b40756a@gmail.com>

On 10/08/2020 1:42 p.m., John Mount wrote:
> I wish I had started with "I am disappointed that lm() doesn't continue its search for weights into the calling environment" or "the fact that lm() looks only in the formula environment and data frame for weights doesn't seem consistent with how other values are treated."

Normally searching is done automatically by following a chain of 
environments.  It's easy to add something to the head of the chain (e.g. 
data), it's hard to add something in the middle or at the end (because 
the chain ends with emptyenv(), which is not allowed to have a parent).

So I'd suggest using

  environment(f) <- environment()

before calling lm() if you want the calling environment to be in the 
search.  Setting it to baseenv() doesn't really make sense, unless you 
want to disable all searches except in data, in which case emptyenv() 
would make more sense (but I haven't tried it, so it might break something).

Duncan Murdoch

> 
> But I did not. So I do apologize for both that and for negative tone on my part.
> 
> 
> Simplified example:
> 
> d <- data.frame(x = 1:3, y = c(1, 2, 1))
> w <- c(1, 10, 1)
> f <- as.formula(y ~ x)
> lm(f, data = d, weights = w)  # works
> 
> # fails
> environment(f) <- baseenv()
> lm(f, data = d, weights = w)
> # Error in eval(extras, data, env) : object 'w' not found
> 
> 
>> On Aug 9, 2020, at 11:56 AM, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
>>
>> This is fairly clearly documented in ?lm:
>>
>



[Rd] lm() takes weights from formula environment
Duncan Murdoch