1
votes

I would like to extract elements from the lower triangle of a matrix to a vector, going from the bottom row to the top row of the matrix.

x <- c(1:10)
M <- matrix(0,5,5)
M[lower.tri(M, diag=FALSE)] <- x

M
#     [,1] [,2] [,3] [,4] [,5]
# [1,]    0    0    0    0    0
# [2,]    1    0    0    0    0
# [3,]    2    5    0    0    0
# [4,]    3    6    8    0    0
# [5,]    4    7    9   10    0

I would like to convert it to this:

x <- c(4, 7, 9, 10, 3, 6, 8, 2, 5, 1)

Thanks for your help.

2

2 Answers

4
votes

You may reorder the lower triangle values according to their row index:

M[lower.tri(M)][order(-row(M)[lower.tri(row(M))])]
# [1]  4  7  9 10  3  6  8  2  5  1
2
votes

Not a beauty:

vec <- numeric()
for ( i in 2:nrow(M) ) {
    vec<- c(M[i, 1:(i-1)], vec)
}

#> vec
# [1]  4  7  9 10  3  6  8  2  5  1