I have a data frame with many Y and X variables. I would like to fit multiple single linear models with lm() by iterating through all of the X and Y variables. I'm working my way to including the other Y variables, but I'm struggling just iterating through the X variables.
My data looks something like this:
set.seed(200)
df <- data.frame(y1 = c(rnorm(n=20, mean = 5)),
y2 = c(rnorm(n=20, mean = 5)),
x1 = c(rnorm(n=20, mean = 13)),
x2 = c(rnorm(n=20, mean = 14)),
x3 = c(rnorm(n=20, mean = 15)))
I have tried multiple ways of fitting these models, but the best way seems to be using a for loop.
models <- list() #creating an empty list
for (i in names(df)[3:5]){ #choosing just the x-variables from the df
models[[i]] <- lm(y1 ~ get(i), df)
}
My outputs are in the models list, and I can access the statistics I want through summary(models[[1]] but I don't want to have to do this for each model that was fit. Is there a way to extract the statistics I want using do.call or map_df or something? Specifically I want the r.squared, residual standard error, p-value, and f.statistic.