在 R 中按行到上三角矩阵的向量 [英] a vector to an upper Triangle matrix by row in R

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

问题描述

我有一个向量说

a = c(1,2,3,4,5,6) 

我想将它们组织成一个上三角矩阵的元素(不考虑对角元素,它们都为零)按行.我的目标是获得以下矩阵:

I would like to organize them into the elements into an upper triangle matrix (without considering diagonal elements, they are all zero) by row. My goal is to get the following matrix:

     [,1] [,2] [,3] [,4]
[1,]    0    1    2    3
[2,]    0    0    4    5
[3,]    0    0    0    6
[4,]    0    0    0    0

但我的以下方法是用这个向量替换对角线元素,但按列分配值.例如,

But the following way I do it is to replace the diagonal elements with this vector but assign values by column. For example,

b= matrix(0, 4, 4)
b[upper.tri(b, diag=FALSE)]=a 

它会给我以下矩阵

   [,1] [,2] [,3] [,4]
[1,]    0    1    2    4
[2,]    0    0    3    5
[3,]    0    0    0    6
[4,]    0    0    0    0

原因是R给矩阵赋值时,默认是按列赋值的.我想知道是否有一种简单的方法可以在不编写 for 循环的情况下解决我的问题.

The reason is that when R assign values to a matrix, by default, it will assign them by column. I am wondering if there is a simple way to solve my problem without writing a for loop.

我之前发现了一个与我的问题相关的类似帖子,但它没有解释按行为上三角矩阵分配值:

I found a similar post before related to my problem but it does not explain assign values to a upper triangle matrix by row:

创建三角矩阵

提前致谢!

推荐答案

这里有一个选项

b[lower.tri(b, diag=FALSE)] <- a
b <- t(b)
b
#      [,1] [,2] [,3] [,4]
# [1,]    0    1    2    3
# [2,]    0    0    4    5
# [3,]    0    0    0    6
# [4,]    0    0    0    0

或者,根据需要重新排序 a 并将其分配到右上角的三角形中:

Alternatively, reorder a as required and assign that into the upper-right triangle:

ut <- upper.tri(b, diag=FALSE)
b[ut] <- a[order(row(ut)[ut], col(ut)[ut])]
b
     [,1] [,2] [,3] [,4]
[1,]    0    1    2    3
[2,]    0    0    4    5
[3,]    0    0    0    6
[4,]    0    0    0    0

这篇关于在 R 中按行到上三角矩阵的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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