Skip to Content

Recombining triads into pairs?

Consider the following matrix:

sequence <- structure(list(C1 = c(2L, 9L, 3L, 9L, 1L, 8L, 9L, 6L, 4L, 5L, 
3L, 2L), C2 = c(3L, 6L, 5L, 8L, 8L, 7L, 3L, 7L, 2L, 1L, 4L, 1L
), C3 = c(8L, 2L, 6L, 4L, 6L, 5L, 7L, 4L, 5L, 9L, 1L, 7L)), .Names = c("C1", 
"C2", "C3"), class = "data.frame", row.names = c(NA, -12L))

Each row has a combination of 3 numbers. I'm trying to recombine all the triads into pairs, with each triad row being divided into three rows (each containing a possible pair). For example, row 1 (2, 3, 8) should be transformed into row 1 (2, 3), row 2 (3, 8) and row 3 (2, 8). The result should look like this:

result <- structure(list(Col1 = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("Row 1", "Row 2", "Row 3"), class = "factor"), 
    Col2 = c(2L, 3L, 2L, 9L, 6L, 9L, 3L, 5L, 3L), Col3 = c(3L, 
    8L, 8L, 6L, 2L, 2L, 5L, 6L, 6L)), .Names = c("Col1", "Col2", 
"Col3"), class = "data.frame", row.names = c(NA, -9L))

(the table repeats until all rows are recombined)

I've tried to do this with combn function: t(combn(unlist(t(sequence)),2)) but this is recombining all elements of the matrix amongst themselves, rather than recombining only the elements of each row. Any light?