Search code examples
rsample

Sample: like Binary Tree Traversal in R


I have 7 pairs of variables: i.e.

["F1", "R1"] ["F2", "R2"]["F3", "R3"]["F4", "R4"]["F5", "R5"]["F6", "R6"]["F7", "R7"]

And would like generate vectors of 7 variables, where each variable is sampled from each group.

The aim is to generate an ergodic sequence of vectors (in this cases, would be 2^7 = 128 possibilities.

Expected results:

     [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]
[1,] 'F1'  'F2'  'F3'  'F4'  'F5'  'F6'  'F7'
[2,] 'F1'  'F2'  'F3'  'F4'  'F5'  'F6'  'R7'
[3,] 'F1'  'F2'  'F3'  'F4'  'F5'  'R6'  'F7'
[4,] 'F1'  'F2'  'F3'  'F4'  'F5'  'R6'  'R7'
[5,] 'F1'  'F2'  'F3'  'F4'  'R5'  'F6'  'F7'
[6,] 'F1'  'F2'  'F3'  'F4'  'R5'  'F6'  'R7'
...

Solution

  • You can fill a matrix with a single for-loop. You just iterate through each column and fill them by repeating the pairs with the rep function. I have parametrized the code so that the number of pairs can vary:

    pairs <- list(c("F1", "R1"), c("F2", "R2"), c("F3", "R3"), c("F4", "R4"),
                   c("F5", "R5"), c("F6", "R6"), c("F7", "R7"))
    dimension <- 7 
    mat <- matrix(0,2^dimension, dimension)
    for(i in 1:dimension){
       mat[,i] <- rep(pairs[[i]], each= 2^(dimension-i))
     }