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

Assuming you’re just using lm the trick is to change the data argument to subset to something different.

speciesList <- unique(df$Species)

for(i in 1:length(speciesList){

    lmmodel <- lm(x ~ year, data = subset(df, Species == speciesList[i]))

    #Now do all the stuff you want with lmmodel, e.g. plot, find slope, etc
}

I’m not going to write a whole piece of functional code for you, but that’s the tricky bit. There’s plenty of resources on how to plot data from models, including trend lines etc.

Using the subset function allows us to pull out the subset of our data one species at a time. I got the species list using unique and then just step through that element by element.

I also wasn’t sure if x or year was your independent variable, so I made the logical assumption it was year.

Browse More Popular Posts

Leave a Comment