Quickly generate the cartesian product of a matrix

后端 未结 5 1957
隐瞒了意图╮
隐瞒了意图╮ 2021-02-09 04:34

Let\'s say I have a matrix x which contains 10 rows and 2 columns. I want to generate a new matrix M that contains each unique pair of rows from

相关标签:
5条回答
  • 2021-02-09 04:34

    Using Dirk's answer:

    idx <- expand.grid(1:nrow(x), 1:nrow(x))
    idx<-idx[idx[,1] >= idx[,2],]
    N <- cbind(x[idx[,2],], x[idx[,1],])
    
    > all(M == N)
    [1] TRUE
    

    Thanks everyone!

    0 讨论(0)
  • 2021-02-09 04:48

    Inspired from the other answers, here is a function implementing cartesian product of two matrices, in the case of two matrices, the full cartesian product, for only one argument, omitting one of each pair:

    cartesian_prod <- function(M1, M2) {
    if(missing(M2)) {  M2 <- M1
         ind  <- expand.grid(1:NROW(M1), 1:NROW(M2))
         ind <- ind[ind[,1] >= ind[,2],] } else {
                                              ind  <- expand.grid(1:NROW(M1), 1:NROW(M2))}
    rbind(cbind(M1[ind[,1],], M2[ind[,2],]))
    

    }

    0 讨论(0)
  • 2021-02-09 04:49

    I'm not quite grokking what you are doing so I'll just throw out something that may, or may not help.

    Here's what I think of as the Cartesian product of the two columns:

    expand.grid(x[,1],x[,2])
    
    0 讨论(0)
  • 2021-02-09 04:50

    The expand.grid() function useful for this:

    R> GG <- expand.grid(1:10,1:10)
    R> GG <- GG[GG[,1]>=GG[,2],]     # trim it to your 55 pairs
    R> dim(GG)
    [1] 55  2
    R> head(GG)
      Var1 Var2
    1    1    1
    2    2    1
    3    3    1
    4    4    1
    5    5    1
    6    6    1
    R> 
    

    Now you have the 'n*(n+1)/2' subsets and you can simple index your original matrix.

    0 讨论(0)
  • 2021-02-09 04:52

    You can also try the "relations" package. Here is the vignette. It should work like this:

    relation_table(x %><% x)
    
    0 讨论(0)
提交回复
热议问题