简体   繁体   中英

How to put a loop in the summary() of a lm-model?

I'm trying to analyse the effects of different distributions. I created two distributions of the type: mu = cumsum [epsilon N(0,1)] + eta N(0,1) mu = cumsum [epsilon N(0,1)] + eta N(0,4)

I have created a linear regression model and want to output the summary, because I'm interested in the R^2. Since the data is different every time I want to create a loop so that the summary is done multiple times and the printed result is the mean of all summaries.

I simply don't know how I could create that loop.

eps = rnorm(200,0,1)
eta200_1 = rnorm(200,0,1)
eta200_4 = rnorm(200,0,4)

y0 = cumsum(eps) + eta200_1
y1 = cumsum(eps) + eta200_4

#The model output that shall be repeated
modely0_y1 = lm(y0 ~ y1)
summary(modely0_y1)

Like so

iterations <- 100
r_squared <- c()

for(i in 1:iterations) {

  eps = rnorm(200,0,1)
  eta200_1 = rnorm(200,0,1)
  eta200_4 = rnorm(200,0,4)

  y0 = cumsum(eps) + eta200_1
  y1 = cumsum(eps) + eta200_4

  modely0_y1 = lm(y0 ~ y1)
  r_squared <- c(r_squared, summary(modely0_y1)$r.squared)


}

r_squared
# [1] 0.8989347 0.7321244 0.5185411 0.7102153 0.4646995 etc

mean(r_squared)
[1] 0.6025012

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM