Get all possible combinations by row in matrix

I have a m x n matrix that looks like this:

 1 2 3 4 5 6 

What is the fastest way to get all possible row combinations? In this case, it will be c(1,4), c(1,5), c(1,6), c(2,4), c(2,5) ... c(3,5), c(3,6)

How to solve this problem using a vectorized approach? In the general case, the matrix m x n would have n^m such combinations.

+6
source share
1 answer

You can use the expand.grid function to get all combinations of elements in each row by building a list of rows with split , as shown here , and passing each element of this list to expand.grid using do.call :

 (m <- rbind(1:3, 4:6)) # [,1] [,2] [,3] # [1,] 1 2 3 # [2,] 4 5 6 do.call(expand.grid, split(m, rep(1:nrow(m), ncol(m)))) # 1 2 # 1 1 4 # 2 2 4 # 3 3 4 # 4 1 5 # 5 2 5 # 6 3 5 # 7 1 6 # 8 2 6 # 9 3 6 

Here is an example with a 3 x 2 matrix instead of a 2 x 3 matrix:

 (m <- matrix(1:6, nrow=3)) # [,1] [,2] # [1,] 1 4 # [2,] 2 5 # [3,] 3 6 do.call(expand.grid, split(m, rep(1:nrow(m), ncol(m)))) # 1 2 3 # 1 1 2 3 # 2 4 2 3 # 3 1 5 3 # 4 4 5 3 # 5 1 2 6 # 6 4 2 6 # 7 1 5 6 # 8 4 5 6 
+6
source

All Articles