Search code examples
rloopsfor-loopnested

Nested for loop with 2 variables/indexes? [R]


I want to combine the two dataset I have. I need to obtain 27 * 27 = 729 data frames. I want to save these data frames in a list (output).

#data sets
R1 <- as.data.frame(expand.grid(rep(list(0:2), 3)))
R2 <- as.data.frame(expand.grid(rep(list(0:2), 3)))

out_list <- list()

for (i in 1:27) {
  for (j in 1:27) {
    output <- rbind(R1[i, ], R2[j, ])
  }
}

How can I run this for loop properly?

The output object must contain 729 data frames.


Solution

  • I would first use expand.grid() to create all combinations of 1:27 and 1:27. Each row of the result would be an i and j pair in your nested for loop. The big thing you're not doing right now is saving the result in the list you created. In your loop, you're overwriting the same object each time without accumulating the results. One benefit of this is that it is easy to see which values of i and j are being used because the ith element of the list corresponds with the ith row of eg.

    #data sets
    R1 <- as.data.frame(expand.grid(rep(list(0:2), 3)))
    R2 <- as.data.frame(expand.grid(rep(list(0:2), 3)))
    
    eg <- expand.grid(1:27, 1:27)
    out_list <- vector(mode="list", length=nrow(eg))
    for(i in 1:nrow(eg)){
      out_list[[i]] <- rbind(R1[eg[i,1], ], R2[eg[i,2], ])
    }
    

    Created on 2024-01-14 with reprex v2.0.2