Reputation: 2233
I have built a simple regression model using the iris data set. I would like to run the dependent variable (iris$Sepal.Length
) with all available variables, each regression with its own variable (each regression should be with . The outcome that I wanted to get is a list of each regression summary. Using the iris data set there should be 4 regressions:
r1 <- lm(Sepal.Length ~ Sepal.Width, data=iris)
r2 <- lm(Sepal.Length ~ Petal.Length, data=iris)
r3 <- lm(Sepal.Length ~ Petal.Width, data=iris)
r4 <- lm(Sepal.Length ~ Species, data=iris)
and a summary with the coefficients for each one of the regressions. Any Ideas how can I do this?
Upvotes: 2
Views: 334
Reputation: 132576
sapply(names(iris)[-1],
function(x) lm.fit(cbind(1, iris[,x]), iris[,"Sepal.Length"])$coef)
# Sepal.Width Petal.Length Petal.Width Species
#x1 6.5262226 4.3066034 4.7776294 4.261333
#x2 -0.2233611 0.4089223 0.8885803 0.791000
Upvotes: 2
Reputation: 55685
library(plyr)
coefs = llply(names(iris)[-1], function(x){
fml = as.formula(sprintf("Sepal.Length ~ %s", x))
coef(lm(fml, data = iris))
})
Upvotes: 2