How to extract a list of TRUE from matrix in R?

Viewed 26

I have been trying to extract all combinations of "TRUE" from a matrix in R. I have 5x5 matrix "MAT" here

     99    70    33    36    93
99  TRUE FALSE FALSE FALSE  TRUE
70 FALSE  TRUE FALSE FALSE FALSE
33 FALSE FALSE  TRUE  TRUE  TRUE
36 FALSE FALSE  TRUE  TRUE FALSE
93  TRUE FALSE  TRUE FALSE  TRUE

`dput(MAT)` 
structure(c(TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, 
FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, 
TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE), dim = c(5L, 5L), dimnames = list(
    c("99", "70", "33", "36", "93"), c("99", "70", "33", "36", 
    "93")))

I would like to list all combinations of T. I also need to remove duplicate combinations since the matrix has symmetric structure. I want an outcome looking like

     [,1] [,2]
[1,]   99   99
[2,]   99   93
[3,]   70   70
[4,]   33   33
[5,]   33   36
[6,]   33   93
[7,]   36   36
[8,]   93   93

I tried apply(MAT,1,function(data)names(which(data==T))) but the outcome was as below. If I can convert from the below outcome to the ideal outcome above, that also works. Thanks for your support!

$99
[1] "99" "93"

$70
[1] "70"

$33
[1] "33" "36" "93"

$36
[1] "33" "36"

$93
[1] "99" "33" "93"
1 Answers

Here's a method that should work.

## generate some sample data
set.seed(42)
MAT = matrix(data = runif(26^2) < 0.25, nrow = 26, dimnames = list(LETTERS, LETTERS))

## convert to long format
long = reshape2::melt(MAT, as.is = TRUE)
## filter down to TRUE values  
## and where the first index is lower to deduplicate the symmetry
long = long[long$value & long$Var1 <= long$Var2, ]
long
#     Var1 Var2 value
# 55     C    C  TRUE
# 80     B    D  TRUE
# 82     D    D  TRUE
# 157    A    G  TRUE
# 158    B    G  TRUE
# 159    C    G  TRUE
# 189    G    H  TRUE
# 214    F    I  TRUE
# 237    C    J  TRUE
# ...
Related