SA12
SA12

Reputation: 318

replace a vector to an upper Triangle matrix with different length

I want to have a triangle matrix by a vector when length of vector is less than replacement length. for example:

v<- c(1,2,3,4,5,6)

and

mat<- matrix(0,5,5).

If I use

mat[upper.tri(mat, diag=FALSE)]<- v

,the result is:

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

But i don't want to replace more than length of vector in matrix. And i want to have:

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

Upvotes: 1

Views: 31

Answers (1)

jay.sf
jay.sf

Reputation: 72803

You could adjust the length of v to that of the upper triangle. This yields some NA values that you can replace with zeroes.

u.tri <- upper.tri(mat, diag=FALSE)
mat[u.tri] <- `length<-`(v, length(u.tri)) 
mat[is.na(mat)] <- 0
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    2    4    0
# [2,]    0    0    3    5    0
# [3,]    0    0    0    6    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    0

Upvotes: 1

Related Questions