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

做~自己de王妃 提交于 2020-01-04 05:55:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!