0

For example, if I have a list of lm objects, how can I pass it to the function anova?

I tried searching for any references to variadic functions in R, or any similar functions to the apply of LISP, with no success.

EDIT: I got it, this can be done via do.call, according to this answer.

Community
  • 1
  • 1
Pedro Silva
  • 4,672
  • 1
  • 19
  • 31

1 Answers1

1

The lapply function is your friend. Here is a complete but nonsensical example:

R> set.seed(42)                      # be reproducible
R> X <- matrix(rnorm(100), ncol=2)
R> y <- vector(mode="list", length=3)
R> y[[1]] <- runif(50); y[[2]] <- rt(50, 3); y[[3]] <- rbinom(50, 5, 0.5)

At this point, we have list with candidate dependent variables, and a common set of regressors. So let's use lapply() to run several regressions at once, and then again to, say, extract coefficients.

R> fits <- lapply(y, FUN=function(z) { lm(z ~ X) })
R> coefs <- lapply(fits, coef)
R> coefs
[[1]]
(Intercept)          X1          X2 
  0.4543939   0.0503187   0.0442636 

[[2]]
(Intercept)          X1          X2 
  0.1115462  -0.0720639   0.1398801 

[[3]]
(Intercept)          X1          X2 
  2.3338105   0.0991485   0.0965852 

R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Thanks for the answer. However, `lapply` works like a map function, transforming each of the elements in its input list. What I need is to pass the entire list at once to `anova` (ie: to compare models). – Pedro Silva Dec 21 '11 at 22:06