简体   繁体   English

如何从 R 中的矩阵中提取 TRUE 列表?

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

I have been trying to extract all combinations of "TRUE" from a matrix in R.我一直在尝试从 R 的矩阵中提取“TRUE”的所有组合。 I have 5x5 matrix "MAT" here我这里有 5x5 矩阵“MAT”

     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.我想列出 T 的所有组合。我还需要删除重复的组合,因为矩阵具有对称结构。 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.我尝试了apply(MAT,1,function(data)names(which(data==T)))但结果如下。 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"

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
# ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM