Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

a vector to an upper Triangle matrix by row in R

I have a vector say

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 

it will give me the following matrix

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

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:

creating a triangular matrix

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's one option

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...