user3928256
user3928256

Reputation: 993

Extract information from matrix in R

I have a boolean matrix like this:

      1     2     3     4     5
1  TRUE FALSE  TRUE FALSE FALSE
2 FALSE  TRUE FALSE FALSE FALSE
3  TRUE FALSE  TRUE FALSE FALSE
4 FALSE FALSE FALSE  TRUE  TRUE
5 FALSE FALSE FALSE  TRUE  TRUE

I need to get the row number and the column number of the TRUE values. However, the values which row number equals column number should be discard, e.g. (1,1) (2,2).... Also, since in the matrix (m,n) = (n,m), I only need one value of the pair, e.g. only (4,5) is needed, not (5,4).

For example, can I get the value into a matrix like this:

    [,1]  [,2]
[1,]   1     3
[2,]   4     5

I've tried which() but don't know how to filter the results. Any suggestion is appreciated. Thanks!

Upvotes: 0

Views: 1388

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

You can also do:

df = data.frame(row=rep(1:(nrow(m)-1),(nrow(m)-1):1),
                col=unlist(sapply(2:ncol(m), function(i) i:ncol(m))))

df[m[upper.tri(m)],]
#   row col
#2    1   3
#10   4   5

Upvotes: 1

C8H10N4O2
C8H10N4O2

Reputation: 18995

Here is your reproducible example:

m <- as.matrix(
      read.table(text = "      1     2     3     4     5
                         1  TRUE FALSE  TRUE FALSE FALSE
                         2 FALSE  TRUE FALSE FALSE FALSE
                         3  TRUE FALSE  TRUE FALSE FALSE
                         4 FALSE FALSE FALSE  TRUE  TRUE
                         5 FALSE FALSE FALSE  TRUE  TRUE")
     )

m[lower.tri(m, diag=TRUE)] <- FALSE # you want to ignore row index >= col index

which(m, arr.ind=TRUE) # returns the TRUEs from the upper triangle

Returns:

  row col
1   1   3
4   4   5

Upvotes: 2

Related Questions