[R] Calling update on an lm-object inside a function
ONKELINX, Thierry
Thierry.ONKELINX at inbo.be
Mon Jan 23 10:44:09 CET 2012
Dear Soren,
I would try adding the new variable to the dataset and use the data = argument of lm
foo <- function(mod, data){
data$y3 <- c(1,3,3,4,6)
update(mod, y3 ~ ., data = data)
}
x <- 1:5
y <- c(1,2,3,3,6)
dataset <- data.frame(x = x, y = y)
mm <- lm(y~x, data = dataset)
foo(mm, dataset)
Best regards,
Thierry
ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek / Research Institute for Nature and Forest
team Biometrie & Kwaliteitszorg / team Biometrics & Quality Assurance
Kliniekstraat 25
1070 Anderlecht
Belgium
+ 32 2 525 02 51
+ 32 54 43 61 85
Thierry.Onkelinx op inbo.be
www.inbo.be
To call in the statistician after the experiment is done may be no more than asking him to perform a post-mortem examination: he may be able to say what the experiment died of.
~ Sir Ronald Aylmer Fisher
The plural of anecdote is not data.
~ Roger Brinner
The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey
-----Oorspronkelijk bericht-----
Van: r-help-bounces op r-project.org [mailto:r-help-bounces op r-project.org] Namens Søren Højsgaard
Verzonden: zondag 22 januari 2012 15:06
Aan: r-help op r-project.org
Onderwerp: [R] Calling update on an lm-object inside a function
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
______________________________________________
R-help op r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list