'Loop and gather results in a table

I am trying to have RStudio to:

  1. run a code 20 times “regression”
  2. gather the results from each regression “Alpha, Beta and Pr value” and give it to me ready in a table format.

Below is the regression code I am using:

xaxis = rnorm(500,0,1)
eval = rnorm(500,0,1)
beta = 0.5
intercept = 1.5
yaxis = intercept + beta*xaxis + eval
Regression_yxe = lm(yaxis ~ xaxis)
summary(Regression_yxe)

Thanks,



Solution 1:[1]

First make your code into a function:

regress <- function () {
    xaxis <- rnorm(500,0,1)
    eval <- rnorm(500,0,1)
    beta <- 0.5
    intercept <- 1.5
    yaxis <- intercept + beta*xaxis + eval
    Regression_yxe <- lm(yaxis ~ xaxis)
    summary(Regression_yxe)$coefficients[, c(1, 4)]
}

Then run the function 20 times:

results <- replicate(20, regress(), simplify=FALSE)

Then combine the results:

do.call(rbind, results)
#              Estimate      Pr(>|t|)
# (Intercept) 1.4764338 2.957601e-124
# xaxis       0.4839075  7.532197e-27
# (Intercept) 1.4521559 5.397893e-117
# xaxis       0.4727487  3.001808e-20
#    . . . .
# (Intercept) 1.5099205 1.406824e-131
# xaxis       0.4963504  1.923430e-24
# (Intercept) 1.4693233 2.519495e-123
# xaxis       0.5008844  5.461081e-25

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dcarlson