a vector to an upper Triangle matrix by row in R

后端 未结 2 505
别跟我提以往
别跟我提以往 2020-12-10 13:35

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

相关标签:
2条回答
  • 2020-12-10 14:05

    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
    
    0 讨论(0)
  • 2020-12-10 14:14

    Note that to fill an ASYMMETRIC matrix you could first fill the upper triangle via the code shown above, then the lower with a DIFFERENT vector (no transpose needed).

      c <- c(7,8,9,10,11,12)
      b[lower.tri(b, diag=FALSE)] <- c
    
    0 讨论(0)
提交回复
热议问题