danluuu
danluuu

Reputation: 23

Converting a vector in R into a lower triangular matrix in specific order

I have a vector where the order of the elements are important, say

x <- c(1,2,3,4)

I would like to arrange my vector into a lower triangular matrix with a specific order where each row contains the preceding element of the vector. My goal is to obtain the following matrix

lower_diag_matrix   
       [,1] [,2] [,3] [,4]
[1,]    4    0    0    0
[2,]    3    4    0    0
[3,]    2    3    4    0
[4,]    1    2    3    4

I know I can fill the lower triangular area using lower_diag_matrix[lower.tri(lower_diag_matrix,diag = T)]<-some_vector but I can't seem to figure out the arrangement of the vector used to fill the lower triangular area. In practice the numbers will be random, so I would need a generic way to fill the area.

Upvotes: 2

Views: 1233

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48211

Here's one way:

x <- c(2, 4, 7)
M <- matrix(0, length(x), length(x))
M[lower.tri(M, diag = TRUE)] <- rev(x)[sequence(length(x):1)]
M
#      [,1] [,2] [,3]
# [1,]    7    0    0
# [2,]    4    7    0
# [3,]    2    4    7

Upvotes: 1

Related Questions