Max Max - 4 days ago 5
R Question

R reverse lower triangle matrix loop

I am trying to fill the lower diagonal of my matrix with a preffilled vector:

My original matrix looks like similar to this:

M 1 2 3 4 5
1 .3 .3 .3 .3 .3
2 .2 .2 .2 .2 .3
3 .1 .1 .1 .1 .1
4 0 0 0 0 0


I have a vector similar to this

V
.4
.3
.25
.1


Now I want to fill the lower triangel with this vector.

0 1 2 3 4 5
1 .3 .3 .3 .3 .1
2 .2 .2 .2 .25 .25
3 .1 .1 .3 .3 .3
4 0 .4 .4 .4 .4


If I use the lowr.tri function it gives out an error so I built a loop which only should fill the columns from the buttom up:

o <- 5
c <- 2
s <- 1
for(s in (1:o)){
for(c in (2:o)){
M[((o-s):o),c] <- V[1:c]}}


My idea was to move upwards like I manually wrote:

M[(5-1):5,2] <- V[1:2]
M[(5-2):5,3] <- V[1:3]


Thank you in advance

Answer

The part of the matrix you want to fill is a reflection of the lower triangular matrix of the original one with respect to row direction, so you can apply a rev function to the lower.tri() result to reverse every row to get the index for replacing the elements, and then it would be straightforward:

Assuming you have matrix M and vector v:

M
#   X1  X2  X3  X4  X5
#1 0.3 0.3 0.3 0.3 0.3
#2 0.2 0.2 0.2 0.2 0.3
#3 0.1 0.1 0.1 0.1 0.1
#4 0.0 0.0 0.0 0.0 0.0

v
# [1] 0.40 0.30 0.25 0.10

lowerIndex = t(apply(lower.tri(M, diag = TRUE), 1, rev))
M[lowIndex] <- (lowIndex * rev(v))[lowIndex]
M

#   X1  X2  X3   X4   X5
#1 0.3 0.3 0.3 0.30 0.10
#2 0.2 0.2 0.2 0.25 0.25
#3 0.1 0.1 0.3 0.30 0.30
#4 0.0 0.4 0.4 0.40 0.40
Comments