try this:

MRfit <- function (...) {
    models <- list(...)
    do.call(anova, models)
}


I hope it helps.

Best,
Dimitris


AC Del Re wrote:
Hi All,

I am interested in creating a function that will take x number of  lm
objects and automate the comparison of each model (using anova). Here
is a simple example (the actual function will involve more than what
Im presenting but is irrelevant for the example):

# sample data:

id<-rep(1:20)
n<-c(10,20,13,22,28,12,12,36,19,12,36,75,33,121,37,14,40,16,14,20)
r<-c(.68,.56,.23,.64,.49,-.04,.49,.33,.58,.18,-.11,.27,.26,.40,.49,
.51,.40,.34,.42,.16)
mod2<-factor(c(rep(c(1,2,3,4),5)))
da<-data.frame(id, n, r, mod1, mod2)


reg0<-lm(da$r ~ 1)
reg1<-lm(da$r ~ da$mod1)
reg2<-lm(da$r ~ da$mod1 + da$mod2)

# This is as far as I get with the function:

MRfit <- function( ...) {
 models <- list(...)
 fit<- anova(models)
 return(fit)
}

MRfit(reg0,reg1,reg2)

# This is what I get from R:

#  Error in UseMethod("anova") :
#  no applicable method for 'anova' applied to an object of class "list"

# which makes sense, but Im not sure how to work with this list
considering the desired output.
# Ideally I would like to get:

MRfit(reg0,reg1,reg2)   # I know that I could just do anova(reg0,reg1,
reg2) but the actual function will have additional functions
integrated

Analysis of Variance Table

Model 1: da$r ~ 1
Model 2: da$r ~ da$mod1
Model 3: da$r ~ da$mod1 + da$mod2

 Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     19 0.83848
2     18 0.78668  1  0.051803 1.1230 0.3060
3     15 0.69193  3  0.094747 0.6847 0.5752


Any help is much appreciated!

Thank you,

AC

______________________________________________
R-help@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.


--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014

______________________________________________
R-help@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.

Reply via email to