0
votes

I wish to get all combinations of elements from a matrix of size m * n.

Sample Example:

1   3   5
2   6   7  

Expected Output:

2 , 1
2 , 3
2 , 5
6 , 1
6 , 3
6 , 5
7 , 1
7 , 3
7 , 5

The rules:

  1. Every combination starts from bottom of matrix and proceeds towards top. It may switch columns though.
  2. Every combination should have number of elements equal to number of rows.
  3. A combination can't have an element from the same row present twice.
  4. Number of columns and rows could vary. So solution has to be generic.

I tried doing this but not getting the exact result

m <- rbind(c(1, 3, 5), c(2, 6, 7))
do.call(expand.grid, split(m, rep(nrow(m):1, ncol(m))))
1
This sounds like a homework question. Please take some time revising How do I ask and answer homework questions?. In short, SO is not a free tutorial/homework service. We are happy to help provided you demonstrate your own effort at solving the problem. Please revise your question to include your code attempt.Maurits Evers
Perhaps you can show your attempt with expand.grid.John Coleman
m <- rbind(c(1,3,5),c(2,6,7)) do.call(expand.grid, split(m, rep(nrow(m):1, ncol(m))))Nrj
its not a homework or anything.. i came accross this problem and was figuring out how to do this in rNrj
@Nrj Please don't post critical clarifications as comments. Edit your post to include (1) your code attempt, and (2) a clear description of where you got stuck and why.Maurits Evers

1 Answers

0
votes

There are many ways,

do.call(
    rbind,lapply(m[2,], function(x){ cbind(x, c(m[1,])) })
)

data:

m<-
structure(c(1L, 2L, 3L, 6L, 5L, 7L), .Dim = 2:3, .Dimnames = list(
    NULL, c("V1", "V2", "V3")))

result:

#   x  
#V1 2 1
#V2 2 3
#V3 2 5
#V1 6 1
#V2 6 3
#V3 6 5
#V1 7 1
#V2 7 3
#V3 7 5

general solution:

do.call(
    rbind,lapply(m[nrow(m),], function(x){ cbind(x, c(m[-nrow(m),])) })
)