[Solved] How to create a loop that will make regression models in R? [closed]


Here’s a solution without loops.

# some artificial data
set.seed(1)
daf <- data.frame(species = factor(paste0("species", c(rep(1:3, 10)))), 
                  year = rep(2000:2009, 3), x = sample(1:100, 30))

library(dplyr)
library(broom)

lm_fit <- daf %>% group_by(species) %>% 
  do(fit = lm(x ~ year, .))

tidy(lm_fit, fit) # or as.data.frame(tidy(lm_fit, fit)) to get a data.frame

# # A tibble: 6 x 6
# # Groups:   species [3]
# species  term          estimate std.error statistic p.value
# <fct>    <chr>            <dbl>     <dbl>     <dbl>   <dbl>
# 1 species1 (Intercept)   2508       7132       0.352   0.734 
# 2 species1 year        -    1.23       3.56   -0.346   0.738 
# 3 species2 (Intercept) -11250       4128      -2.73    0.0260
# 4 species2 year             5.64       2.06    2.74    0.0256
# 5 species3 (Intercept)    461       7460       0.0618  0.952 
# 6 species3 year        -    0.206      3.72   -0.0554  0.957 

library(ggplot2)
ggplot(daf, aes(x = year, y = x)) + geom_smooth(method = "lm", se = FALSE) +
  facet_wrap(~species)

enter image description here

solved How to create a loop that will make regression models in R? [closed]