将R中的向量按特定顺序转换为下三角矩阵 [英] Converting a vector in R into a lower triangular matrix in specific order

查看:123
本文介绍了将R中的向量按特定顺序转换为下三角矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量,其中元素的顺序很重要,例如

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

我知道我可以使用lower_diag_matrix[lower.tri(lower_diag_matrix,diag = T)]<-some_vector填充下部三角形区域,但是我似乎无法弄清楚用于填充下部三角形区域的向量的排列方式.实际上,这些数字是随机的,因此我需要一种通用的方法来填充区域.

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.

感谢进阶!

推荐答案

这是一种方法:

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

这篇关于将R中的向量按特定顺序转换为下三角矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆