persephone
persephone

Reputation: 420

All possible combinations of matrices with values from vectors

How to get all possible 2 by v matrices, where v is the number of vectors with arbitrary length, filled with the values of a vector.

For instance, I got three vectors A = c(1,2,3) B = c("x","z") C = c(1,0).

Suppose now, I want to get all possible 2 by 3 matrices or data frames which stem from the values of the above vectors.

In the end, I would like to have something like this:

       combination_id first_row A B C
    1:              1         1 0 x 0
    2:              2         0 1 x 1
    3:              3         1 1 z 0
    4:              4         0 0 z 1
    5:              5         1 0 x 0
    6:              6         0 1 x 0
    7:              :               
    8:              :               

Upvotes: 1

Views: 340

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173928

This gives every possible combination of two elements from each set (where replacement is allowed), giving a total of 144 matrices. These are then bound together to give a single 288-row data frame:

A = c(1,2,3) 
B = c("x","z") 
C = c(1,0)

df <- setNames(as.data.frame(do.call(rbind, 
      lapply(as.data.frame(t(expand.grid(A, B, C, A, B, C))), 
             matrix, nrow = 2, byrow = TRUE))), 
      c("A", "B", "C"))

head(df)
#>   A B C
#> 1 1 x 1
#> 2 1 x 1
#> 3 2 x 1
#> 4 1 x 1
#> 5 3 x 1
#> 6 1 x 1

nrow(df)
#> [1] 288

Created on 2020-09-06 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions