2

I have an R dataframe with 14 columns and 5 rows (without headers and row names), and I would like to extract all of the possible column pairs, unique if possible.

For example, my input dataframe:

    C1  C2  C3  C4  C5  C6  C7  C8  C9  C10 C11 C12 C13 C14
A   1   1   1   0   1   0   1   0   0   1   0   1   0   0
B   0   1   0   0   1   0   0   1   1   0   1   1   0   0
C   1   0   1   1   1   0   0   0   0   1   1   1   1   1
D   1   1   1   1   1   1   1   0   0   0   1   1   0   0
E   1   0   0   1   0   1   1   1   0   1   1   1   1   1

And I would like to get all possible 91 unique pairs, like:

    C1  C2
A   1   1
B   0   1
C   1   0
D   1   1
E   1   0
    C1  C3
A   1   1
B   0   0
C   1   1
D   1   1
E   1   0

And so on, if at all possible in different dataframes

Thank you!

Carlos
  • 35
  • 3

1 Answers1

0

We could use combn to do pairwise combination

out <- combn(df1, 2, simplify = FALSE)

-output

> length(out)
[1] 91
> out[[1]]
  C1 C2
A  1  1
B  0  1
C  1  0
D  1  1
E  1  0

data

df1 <- structure(list(C1 = c(1L, 0L, 1L, 1L, 1L), C2 = c(1L, 1L, 0L, 
1L, 0L), C3 = c(1L, 0L, 1L, 1L, 0L), C4 = c(0L, 0L, 1L, 1L, 1L
), C5 = c(1L, 1L, 1L, 1L, 0L), C6 = c(0L, 0L, 0L, 1L, 1L), C7 = c(1L, 
0L, 0L, 1L, 1L), C8 = c(0L, 1L, 0L, 0L, 1L), C9 = c(0L, 1L, 0L, 
0L, 0L), C10 = c(1L, 0L, 1L, 0L, 1L), C11 = c(0L, 1L, 1L, 1L, 
1L), C12 = c(1L, 1L, 1L, 1L, 1L), C13 = c(0L, 0L, 1L, 0L, 1L), 
    C14 = c(0L, 0L, 1L, 0L, 1L)), class = "data.frame", row.names = c("A", 
"B", "C", "D", "E"))
akrun
  • 874,273
  • 37
  • 540
  • 662