[R] Calling update on an lm-object inside a function

Søren Højsgaard sorenh at math.aau.dk
Sun Jan 22 15:06:07 CET 2012


Dear all,
I want to update an lm (or glm) object by changing the response variable and I want to do so inside a function. Doing the update outside 
of a function is straight forward:
 
 x <- 1:5
 y <- c(1,2,3,3,6)
 mm <- lm(y~x)
 y2 <- c(1,3,3,4,6)
 mm2<- update(mm, y2 ~ .)
 
But I want to make the update inside a function (where the new response variable is declared 
inside the function). If I do 
 
 foo <- function(mod){
   y3 <- c(1,3,3,4,6)
   update(mod, y3 ~ .)
 }
Then I get 
 foo(mm)

Error in eval(expr, envir, enclos) : object 'y3' not found
(because y3 is not known in the global environment - I suppose). To fix this I do
  
 foo2 <- function(mod){
   y3 <- c(1,3,3,4,6)
   mod2 <- eval(getCall(mod))
   update(mod2, y3 ~ .)
 }
 foo2(mm)

Call:
lm(formula = y3 ~ x)

Coefficients:
(Intercept)            x  
        0.1          1.1  

Question: Is this the "appropriate" way of making such a model "available" for an update inside a function, 
or is there a better way? I guess so - because:
If I change the model formula of my model and then invoke foo2 I get

mm3 <- update(mm,.~.-x)
> foo2(mm3)
Error in eval(expr, envir, enclos) : object 'y3' not found

This puzzles me. Question: can anyone help me clarify why this happens and what I can do to fix it.

Thanks in advance
Søren



More information about the R-help mailing list