Agrii Enginee
Agrii Enginee

Reputation: 75

Convert upper triangular part of a matrix to 3-column long format

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

Upvotes: 8

Views: 2238

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73285

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])

Upvotes: 9

Related Questions