David Z
David Z

Reputation: 7041

How to extract symmetrix matrix information to a data frame in R

Suppose I have a symmetrix matrix:

 cnt<-c(1,2,3,4,2,3,1,6,3,1,4,3,4,6,3,5)
 m<-matrix(cnt, nrow=4, byrow=T)
 colnames(m)<-rownames(m)<-LETTERS[1:4]
 m
  A B C D
A 1 2 3 4
B 2 3 1 6
C 3 1 4 3
D 4 6 3 5

What I wanted is to extract the upper diagonal counts to a pair wise data frame such like:

    A-B 2
    A-C 3
    A-D 4
    B-C 1
    B-D 6
    C-D 3

Upvotes: 2

Views: 30

Answers (2)

GKi
GKi

Reputation: 39657

In base and looking at the source of upper.tri it can be done with:

d <- dim(m)
tt <- which(.row(d) < .col(d), arr.ind=TRUE)
data.frame(rc=paste(rownames(m)[tt[,1]], colnames(m)[tt[,2]], sep="-"), m=m[tt])
#   rc m
#1 A-B 2
#2 A-C 3
#3 B-C 1
#4 A-D 4
#5 B-D 6
#6 C-D 3

Upvotes: 3

akrun
akrun

Reputation: 887108

We just replace the upper.tri with NA, melt into 'long' format and unite the columns

library(reshape2)
library(dplyr)
m[upper.tri(m, diag = TRUE)] <- NA
melt(m, na.rm = TRUE)  %>%
     unite(Var1, Var2, Var1)
#   Var1 value
#2   A_B     2
#3   A_C     3
#4   A_D     4
#7   B_C     1
#8   B_D     6
#12  C_D     3

Upvotes: 2

Related Questions