-1

I have the following cross-correlation matrix:

df =

   A B C
A  1 7 1
B  7 1 9
C  1 9 1

and I would like to make it into the following format:

A B 7
A C 1
B C 9

any straightforward R code that can do such thing?

Economist_Ayahuasca
  • 1,648
  • 24
  • 33
  • Get the ["SOfun" package](http://mrdwab.github.io/SOfun/index.html) and do `library(SOfun); dist2df(as.dist(mat))`. Or perhaps do `as.data.frame(as.table(mat))[lower.tri(mat), ]`. – A5C1D2H2I1M1N2O1R2T1 Feb 15 '21 at 22:48

2 Answers2

1

Not a straightforward way but an option in base R :

mat[upper.tri(mat, diag = TRUE)] <- NA
tmp <- which(!is.na(mat), arr.ind = TRUE)
data.frame(col = colnames(mat)[tmp[, 2]], row = rownames(tmp), val = mat[tmp])

#  col row val
#1   A   B   7
#2   A   C   1
#3   B   C   9

data

mat <- structure(c(1L, 7L, 1L, 7L, 1L, 9L, 1L, 9L, 1L), .Dim = c(3L, 
3L), .Dimnames = list(c("A", "B", "C"), c("A", "B", "C")))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Another base R option

inds <- which(col(mat) < row(mat), arr.ind = TRUE)
data.frame(
  col = colnames(mat)[inds[, "col"]],
  row = rownames(mat)[inds[, "row"]],
  val = mat[inds]
)

gives

  col row val
1   A   B   7
2   A   C   1
3   B   C   9
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81