[Rd] weights in lm, glm (PR#9023)

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Jun 22 22:43:04 CEST 2006


jsignoro at hsph.harvard.edu writes:

> Full_Name: James Signorovitch
> Version: 2.2.1
> OS: WinXP
> Submission from: (NULL) (134.174.182.203)
> 
> 
> In the code below, fn1() and fn2() fail with the messages given in the comments.
>  Strangely, fn2() fails for all data sets I've tried except for those with 100
> rows.  
> The same errors occur if glm() is used in place of lm(), or if R 2.1.1 is used
> on a unix system.  Thanks for looking into this.  JS 
> 
> fn1 <- function(model, data)
> {
> 	w <- runif(nrow(data));
> 	print(lm(model, data=data, weights=w));		
> }
> 
> fn2 <- function(model, data)
> {
> 	print(lm(model, data=data, weights=runif(nrow(data))));	
> }
> 
> n = 101;
> 
> A <- data.frame(matrix(rnorm(2*n), n, 2));
> names(A) <- c("x", "y");
> 
> # we can run the command
> print(lm(y ~ x, data=A, weights=runif(nrow(A))));
> 
> # But fn1() generates the error message
> # 
> # Error in eval(expr, envir, enclos) : object "w" not found
> #
> 
> fn1(y ~ x, data=A);
> 
> # fn2() generates the error message:
> # Error in model.frame(formula, rownames, variables, varnames, extras,
> extranames,  : 
> #       variable lengths differ
> #
> #
> # But fn2() works if n=100
> 
> fn2(y ~ x, data=A);
> 
> # note: the error in fn1() still occurs if w <- 1:nrow(data);
> 

This is due to the concept of a model environment (which does not
contain w). This is a deliberate design, not a bug.

The rationale is a bit convoluted, but it ensures that

w <- runif(nrow(A))
fn1(y  ~ x + w, data=A)

picks up w from the global environment, not the evaluation frame of
fn1, and the convention is that weight, subset, and offset arguments
are picked from the same environment as the variables in the formula.

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-devel mailing list