Search code examples
rmatrixcombinationsrbindcbind

How to fill all combinations from a matrix to two columns


I'm doing this:

data.2<-
rbind(
cbind(data[,1], data[,2]),
cbind(data[,1], data[,3]),
cbind(data[,1], data[,4]),
cbind(data[,1], data[,5]),
cbind(data[,1], data[,6]),
cbind(data[,1], data[,7]),
cbind(data[,1], data[,8]),
cbind(data[,1], data[,9]),
cbind(data[,1], data[,10]),
cbind(data[,1], data[,11]))

What can I do if I have a lot more columns and I don't want to cbind every combination manually?

data is e.g.

      [,1] [,2] [,3] [,4]
 [1,]    1    4    2     5
 [2,]    2    5    6     7
 [3,]    3    6    8     9
and should look like
     [,1] [,2]
 [1,]    1    4
 [2,]    2    5
 [3,]    3    6
 [4,]    1    2
 [5,]    2    6
 [6,]    3    8
 [7,]    1    5
 [8,]    2    7
 [9,]    3    9

I have hundrets of columns and rows and I never know how much!


Solution

  • Since first column is always repeating, you could use recycling like so:

    data <- matrix(1:33, 3, 11)
    
    data.2 <- cbind(data[, 1], as.numeric(data[, -1]))
    

    Result

    > data.2
          [,1] [,2]
     [1,]    1    4
     [2,]    2    5
     [3,]    3    6
     [4,]    1    7
     [5,]    2    8
     [6,]    3    9
     [7,]    1   10
     [8,]    2   11
     [9,]    3   12
    [10,]    1   13
    [11,]    2   14
    [12,]    3   15
    [13,]    1   16
    [14,]    2   17
    [15,]    3   18
    [16,]    1   19
    [17,]    2   20
    [18,]    3   21
    [19,]    1   22
    [20,]    2   23
    [21,]    3   24
    [22,]    1   25
    [23,]    2   26
    [24,]    3   27
    [25,]    1   28
    [26,]    2   29
    [27,]    3   30
    [28,]    1   31
    [29,]    2   32
    [30,]    3   33