Quickly generate the cartesian product of a matrix

后端 未结 5 1958
隐瞒了意图╮
隐瞒了意图╮ 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!

提交回复
热议问题