Search code examples
rdataframematrixnested-loops

How to create a dataframe with nested forloops in r


I would like to create a simple data-frame with a nested for loop.

I would like every possibly assembly of 1:3 for A, B and C using a for loop.

This is what I have so far:

for (A in 1:3) {
  for (B in 1:3) {

output[A,]<-A
  }

  }

This is what I would Like it to look like:

enter image description here


Solution

  • For loop is very slow in R. Try to use expand_grid.

    library(tidyr)
    
    expand_grid(
      A = 1,
      B = 1:3,
      C = 1:3
    )
    
    # A tibble: 9 x 3
          A     B     C
      <dbl> <int> <int>
    1     1     1     1
    2     1     1     2
    3     1     1     3
    4     1     2     1
    5     1     2     2
    6     1     2     3
    7     1     3     1
    8     1     3     2
    9     1     3     3