'Is it possible to cbind multiple iterations of a nested for loop?

I've got a nested for loop

and I'm trying to do it so that multiple iterations of the nested for loop

the end of the for loops looks like this:

reps MAD
5 23
10 21
20 19
30 17
40 15
50 12

And with every new iteration, I want it to add a column so that it looks like this:

reps MAD MAD2
5 23 25
10 21 22.5
20 19 20
30 17 19
40 15 17
50 12 15
out <- list()
output <- list()
i <- 1

for(patient in c("P01", "P02", "P03", "P04", "P05")){
  for(period in c("SBP", "Laser_Mean")){
    for(reps in c(5,10,20,30,40,50)){
        for(isim in 1:20){
          print(reps)
        
          db_temp <- db_s_abs_fix%>%
            filter(Patient==patient)%>%
            filter(Period==period)%>%
            group_by(Patient, Target_num, Period, Type)%>%
            sample_n(reps, replace=TRUE)
        
          last_delay <- matt_predict(db_temp)
          print(patient)
          print(period)
          print(reps)
          print(last_delay$delay)
        
          out[[i]] <- data.frame(patient=patient, period=period, reps=reps, delay=last_delay$delay, isim=isim)
          i <- i+1
      
      }

      
    }
  }
  out <- bind_rows(out)
  
    
  d_bp02 <- out%>%
    filter(period == "SBP")%>%
    dplyr::select(patient,
                  reps,
                  AV_BP = delay)
  
  d_laser02 <- out%>%
    filter(period == "Laser_Mean")%>%
    dplyr::select(patient,
                  reps,
                  AV_Laser = delay)
  
  d_final02 <- full_join(d_bp02, d_laser02)%>%
    group_by(reps)%>%
    mutate(av_diff = AV_Laser - AV_BP,
           abs_av_diff = abs(av_diff))
  
  d_final_mad <- d_final02%>%
    group_by(reps)%>%
    summarise(med_av_diff = median(av_diff),
              med_abs_av_diff = median(abs(av_diff)),
              MAD = median(abs(av_diff - med_av_diff)))
  
  d_final_mad <- d_final_mad%>%
    group_by(reps)%>%
    dplyr::select(reps,MAD)
  
  output[[i]] <- d_final_mad
  i <- i+1
  
}

  output <- do.call(cbind,output)

I have tried:

  output <- do.call(cbind,output)

stats <- foreach(i = 1:5, .combine=data.frame) %do% {
  output(i)
}

do.call(cbind, lapply(output, as.data.frame))

The above don't work

for (i in 1:5) {
  d_final_mad$i <- i  #to keep track of which iteration produced it
  output[[i]] <- d_final_mad # add it to your list
}

This one just gives me the same result 5 times



Sources

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

Source: Stack Overflow

Solution Source