Re: [S] model.frame()

Prof Brian Ripley (
Tue, 3 Nov 1998 12:38:19 +0000 (GMT)

>From Adrian Baddeley <>

> Forgive me if this is a FAQ:

A variant on one!

> try <- function(fmla, data, wt) {
> lm(fmla, data = data, weights = wt)
> }
> looks for the object 'wt' in the frame that called try(),
> rather than using the 'wt' argument in the function.
> (transcript below.)
> Is this really the intention?

It is not totally clear what is the intention, as this is done by
internal code in model.frame.default. However, help(lm) says

data: a data.frame in which to interpret the variables named
in the formula, or in the subset and the weights argument.
If this is missing, then the variables in the formula
should be on the search list.

and this does suggest that in fact it is looking in frame 0 (rather
than in `frame that called try()', which in your examples happens to be
0). The frame of try() is not on the relevant search list (and let us
not start to debate if it should be all over again).

> I have been using
> assign(".wt", wt, sys.parent())

I think that should be in frame=1, as otherwise further nesting will not work:

xx <- seq(0,1,by=0.01)
yy <- xx + rnorm(101)
dd <- data.frame(x=xx,y=yy)
ww <- rep(1,length(xx))
try <- function(fmla, data, wt)
assign(".wt", wt, sys.parent())
lm(fmla, data = data, weights = .wt)
try(y ~ x, dd, ww) # OK

try2 <- function()
ww2 <- rep(1,length(xx))
try(y ~ x, dd, ww2)
try2() # Error in try(y ~ x, dd, ww2): Object ".wt" not found

try <- function(fmla, data, wt)
assign(".wt", wt, f=1)
lm(fmla, data = data, weights = .wt)
try2() # works.

> What is the recommended workaround?

Add wt to the data frame `data'. It searches for weights there first.
As in

try <- function(fmla, data, wt) {
lm(fmla, data = cbind(data, wt=wt), weights = wt)


Brian D. Ripley,        
Professor of Applied Statistics,
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

----------------------------------------------------------------------- This message was distributed by To unsubscribe send e-mail to with the BODY of the message: unsubscribe s-news