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))
source share