[R] Loop over regression results

Ronald Kölpin ronald.koelpin at gmail.com
Mon Feb 16 14:36:43 CET 2015


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Dear all,

I have a problem when trying to present the results of several
regression. Say I have run several regressions on a dataset and saved
the different results (as in the mini example below). I then want to
loop over the regression results in order so save certain values to a
matrix (in order to put them into a paper or presentation).

Aside from the question of how to access certain information stored by
lm() (or printed by summary()) I can't seem to so loop over lm()
objects -- no matter whether they are stored in a vector or a list.
They are always evaluated immediately when called. I tried quote() or
substitute() but that didn't work either as "Objects of type 'symbol'
cannot be indexed."

In Stata I would simply do something like

forvalues k = 1/3 {
 quietly estimates restore mod`k'
// [...]
}

and I am looking for the R equivalent of that syntax.

Kind regard and thanks

RK


attach(iris)
mod1 <- lm(Sepal.Width ~ Petal.Width, data=iris, subset=Species=="setosa")
mod2 <- lm(Sepal.Width ~ Petal.Width, data=iris,
subset=Species=="versicolor")
mod3 <- lm(Sepal.Width ~ Petal.Width, data=iris,
subset=Species=="virginica")

summary(mod1); summary(mod2); summary(mod3)

mat <- matrix(data=NA, nrow=3, ncol=5,
              dimnames=list(1:3, c("Model", "Intercept", "p(T > |T|)",
"Slope", "R^2")))

mods <- c(mod1, mod2, mod3)

for(k in 1:3)
{
    mod <- mods[k]
    mat[2,k] <- as.numeric(coef(mod))[1]
    mat[3,k] <- as.numeric(coef(mod))[1]
}
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iQEcBAEBAgAGBQJU4fJnAAoJEKdHe5EUSrVeafwIALerOj+rsZTnbSKOUX6vYpr4
Uqsx0X2g+IgJw0KLdyqnlDmOut4wW6sWExtVgiugo/bkN8g5rDotGAl06d0UYRQV
17aLQqQjI6EGXKV9swwlm2DBphtXCIYUCXnDWUoG4Y2wC/4hDnaLbZ9yJFF1GSjn
+aN/PFf1mPPZLvF1NgMmzLdszP76VYzEgcOcEUfbmB7RU/2WEBLeBYJ8+FD1utPJ
cnh03rSc/0dgvphP8FO47Nj7mbqqhKL76a9oQqJSJiZJoCFCGiDIIgzq7vwGWc4T
9apwC/R3ahciB18yYOSMq7ZkVdQ+OpsqDTodnnIIUZjrVIcn9AI+GE0eq1VdLSE=
=x+gM
-----END PGP SIGNATURE-----



More information about the R-help mailing list