7

I want Convert matrix to three defined columns in R. This is an example:

input

     col1  col2  col3
row1  1     2     3 
row2  2     3     4
row3  3     4     5

output:

row1 clo1 1
row1 col2 2
row1 col3 3
row2 col2 3
row2 col3 4
row3 col3 5
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248

1 Answers1

8

Suppose X is your matrix, we can do:

ind <- which(upper.tri(X, diag = TRUE), arr.ind = TRUE)
cbind(ind, X[ind])

In some cases you may want to use dim names. In that case, we have to arrange the result in a data frame, as the first two columns are character, while the third column is numeric.

ind <- which(upper.tri(X, diag = TRUE), arr.ind = TRUE)
nn <- dimnames(X)
data.frame(row = nn[[1]][ind[, 1]],
           col = nn[[2]][ind[, 2]],
           val = X[ind])
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248