How to create a list of regression models for predefined vectors in R?

R ProgrammingServer Side ProgrammingProgramming

To create a list of regression models for predefined vectors, we can create a blank list and then use the for loop to create the list of regression models. For example, if we have two vectors say x and y, and we want to create a list of regression model between x and y then we create a blank list using list() and perform for loop a particular number of times as shown in the below examples.

Example1

 Live Demo

x<-rnorm(20)
y<-rnorm(20)
List_1=list()
for (i in 1:10) List_1[[i]] = lm(y~x)
List_1

Output

[[1]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[2]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[3]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[4]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[5]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[6]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[7]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[8]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[9]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

[[10]]
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
   -0.1294 0.2600

Example 2

 Live Demo

x1<-rpois(2000,1)
x2<-rpois(2000,2)
x3<-rpois(2000,2)
y1<-rpois(2000,5)
List_2=list()
for (i in 1:10) List_2[[i]] = lm(y1~x1+x2+x3)
List_2

Output

[[1]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
   5.065561 -0.039094 0.006488 -0.035636

[[2]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
   5.065561 -0.039094 0.006488 -0.035636

[[3]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
   5.065561 -0.039094 0.006488 -0.035636

[[4]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
 5.065561 -0.039094 0.006488 -0.035636

[[5]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
   5.065561 -0.039094 0.006488 -0.035636

[[6]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
 5.065561 -0.039094 0.006488 -0.035636

[[7]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
 5.065561 -0.039094 0.006488 -0.035636

[[8]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
 5.065561 -0.039094 0.006488 -0.035636

[[9]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
 5.065561 -0.039094 0.006488 -0.035636

[[10]]
Call:
lm(formula = y1 ~ x1 + x2 + x3)
Coefficients:
(Intercept) x1 x2 x3
 5.065561 -0.039094 0.006488 -0.035636
raja
Published on 06-Mar-2021 11:21:45
Advertisements