Search code examples
rnested-loops

Nested loops in R multiple replacement length


I am trying to create a loop that would generate the following:

[1] 1 1
[2] 1 2
[3] 1 3
[4] 2 1
[5] 2 2
[6] 2 3
[7] 3 1
[8] 3 2
[9] 3 3

Using the following code:

b<-list()
for (k in 1:9){
  for (i in 1:3) {
    for (j in 1:3){
      b[k]<- c(i,j)
    }
  }
}

But it doesn't work


Solution

  • This is just a cross join of 1:3 with 1:3

    data.table::CJ(1:3, 1:3)
    

    But, if you wanted to use a loop you could do

    b <- list()
    k <- 0
    for (i in 1:3) {
        for (j in 1:3){
          k    <- k + 1
          b[[k]] <- c(i,j)
        }
    }
    b