0

I would like to run each model 10 times at each level of introduced standard deviation (for a total of 21 'levels'), each time with different generated normal distributions. However, the models are only being run once at each level of standard deviation. The output I am looking for is a total of 10 p-values and 10 AIC values at each level of standard deviation.

I apologize in advance if this is trivial; I've been trying to figure out this code for several days now and looked around in other previously asked questions that had this similar problem so that I did not have to post this, but I am still unable to figure it out. I would greatly appreciate any insight on this.

output=list()
for (k in 1:21) {
  N<-100
  M<- 2000
  SD1<- 500
  SD2<- k*10-10
  aicM1 = c()
  aicM2 = c()
  aicM3 = c()
  pM1 = c()
  pM2 = c()
  pM3 = c()
  pM4 = c()
  Slope<-3
  Slope1<-0
  Intercept<-0 
  for (i in 1:10) {
    # Old data 
      Area<-rnorm(N, M, SD1)
      Prec<-rnorm(N, M, SD1)
      SR<-Intercept+ Slope*Area + Slope1*Prec + rnorm(N,0,SD2)
      old<-as.data.frame(cbind(Area, Prec, SR))
      # New data
      Area1 = rnorm(N, M, SD1)
      Prec1 = rnorm(N, M, SD1)
      SR1<-Intercept+ Slope1*Area + Prec1 + rnorm(N,0,SD2)
      new<-as.data.frame(cbind(Area1, Prec1, SR1))
      # Linear models
      M1<-lm(old$SR~old$Area)
      M2<-lm(old$SR~old$Prec)
      M3<-lm(old$SR~old$Area + old$Prec)
      M4<-lm(old$SR~1)
      # p-values
      pM1 <- c({fstat <- summary(M1)$fstatistic
      pf(fstat[1], fstat[2], fstat[3], lower.tail=FALSE)})
      pM2 <- c({fstat <- summary(M2)$fstatistic
      pf(fstat[1], fstat[2], fstat[3], lower.tail=FALSE)})
      pM3 <- c({fstat <- summary(M3)$fstatistic
      pf(fstat[1], fstat[2], fstat[3], lower.tail=FALSE)})
      pM4 <- c(coef(summary(M4))[, "Pr(>|t|)"])
      # AIC Values 
      aicM1 = c(AIC(M1))
      aicM2 = c(AIC(M2))
      aicM3 = c(AIC(M3))
  }
    # the eight rows to put the values in 
    uwyz<-cbind(aicM1, aicM2, aicM3, pM1, pM2, pM3, pM4, 10*k-10)
    mean(uwyz[,1])
    mean(uwyz[,2])
    mean(uwyz[,3])
    mean(uwyz[,4])
    mean(uwyz[,5])
    mean(uwyz[,6])
    mean(uwyz[,7])
    mean(uwyz[,8])
  
  output[[k]]<-uwyz
}
  

outfinal= as.data.frame(do.call(rbind, output))
outfinalSumm<-outfinal %>%
  group_by(V8) %>%
  summarize(FinalpM1 = (pM1), FinalpM2 = (pM2), FinalpM3 = (pM3), FinalpM4 = (pM4), FinalaicM1 = (aicM1), FinalaicM2 = (aicM2), FinalaicM3 = (aicM3))

outfinalSumm2<-as.matrix(outfinalSumm)
FinalData <- as.data.frame(outfinalSumm)
Phil
  • 7,287
  • 3
  • 36
  • 66
  • Given how you are using the loop iterations, you could avoid the need for a nested loop by creating a loop index using `loop_index <- expand.grid(1:21, 1:10)`, and then do one loop `for (i in loop_index)` and then call `loop_index[i,1]` and `loop_index[i,2]` as needed. – Phil Dec 17 '22 at 21:01

0 Answers0