1

I have a vector where the order of the elements are important, for example:

v<-c(1,2,3,4,5,6,7,8,9,10)

I would like to arrange my vector into a lower/upper triangular matrix with a specific order:

1 2 4 7
0 3 5 8
0 0 6 9
0 0 0 10

or

1 0 0 0
2 3 0 0
4 5 6 0
7 8 9 10

I think I can make it whith a for, but I don't know how, and blanks could be filled with NAs or 0's

thanks

Beth
  • 127
  • 6

1 Answers1

4

You can fill up the upper triangular matrix by doing

mat <- matrix(0, nrow = 4, ncol = 4)
mat[upper.tri(mat, diag = TRUE)] <- v

mat
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    4    7
#[2,]    0    3    5    8
#[3,]    0    0    6    9
#[4,]    0    0    0   10

Lower triangle doesn't follow the same sequence as upper triangle so doing

mat[lower.tri(mat, diag = TRUE)] <- v

doesn't give the expected outcome.

We can get the indices of lower triangle, order them according to row and then update the matrix

order_mat <- which(lower.tri(mat, diag = TRUE), arr.ind = TRUE)
mat[order_mat[order(order_mat[, 1]), ]]  <- v

mat
#     [,1] [,2] [,3] [,4]
#[1,]    1    0    0    0
#[2,]    2    3    0    0
#[3,]    4    5    6    0
#[4,]    7    8    9   10

Or as @Gregor commented a much simpler way is to transpose the upper triangular result

mat <- matrix(0, nrow = 4, ncol = 4)
mat[upper.tri(mat, diag = TRUE)] <- v #Upper triangle
t(mat)   #Lower triangle
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213