Quickly generate the cartesian product of a matrix

后端 未结 5 1951
隐瞒了意图╮
隐瞒了意图╮ 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: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.

提交回复
热议问题