Quickly generate the cartesian product of a matrix

后端 未结 5 1959
隐瞒了意图╮
隐瞒了意图╮ 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: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],]))
    

    }

提交回复
热议问题