Let’s say that we want to run a different regression model for each Species
in iris
dataset. We can do it in two different ways as follows:
Store the models in a list
my_models<-list() for (s in unique(iris$Species)) { tmp<-iris[iris$Species==s,] my_models[[s]]<-lm(Sepal.Length~Sepal.Width+Petal.Length+Petal.Width, data=tmp) } # get the 'setosa' model my_models[['setosa']]
Call:
lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width,
data = tmp)
Coefficients:
(Intercept) Sepal.Width Petal.Length Petal.Width
2.3519 0.6548 0.2376 0.2521
Store the models by name using the assign
for (s in unique(iris$Species)) { tmp<-iris[iris$Species==s,] assign(s,lm(Sepal.Length~Sepal.Width+Petal.Length+Petal.Width, data=tmp)) } # get the 'setosa' model get("setosa")
Call:
lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width,
data = tmp)
Coefficients:
(Intercept) Sepal.Width Petal.Length Petal.Width
2.3519 0.6548 0.2376 0.2521