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

查看:469
本文介绍了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天全站免登陆