Hi. this is my failed attempt at another question. How can I do regression inside a loop that changes the independent variable each time?
My lm statement is not assigning the independent variable. Thank you.
If you want to keep the results for every regression, add a list object in front of the loop of @FJCC answer:
df <- data.frame(mtcars)
indepvars <- colnames(df[3:7])
summary <- data.frame()
# new:
model <- vector('list', length = length(indepvars))
for (i in 1:5){
model[[i]] <- lm(paste("mpg ~", indepvars[i]), df)
summary[i,1] <- model[[i]]$coefficients[1]
summary[i,2] <- model[[i]]$coefficients[2]
}
However, for usal regression with lm you could create a variable, containing all formulas to use and then use purrr::map() to perform a linear model for every specified formula (with lm you can also use broom to get the most important results in a tidy way, e.g. as a data.frame).