问题
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.
Thanks in advanced!
回答1:
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
来源:https://stackoverflow.com/questions/48468869/converting-a-vector-in-r-into-a-lower-triangular-matrix-in-specific-order