0
votes

I am trying to replace the upper triangle of a matrix with the lower triangle of the matrix when the lower triangle entries are equal to a given value. For example, I have the following matrix:

0 0 0 
1 0 0 
2 1 0 

I need to copy all lower triangle entries that are equal to 1 to the upper triangle. The result should be:

0 1 0 
1 0 1 
2 1 0 

I tried using:

library(gdata)

z <- matrix(c(0,1,2,0,0,1,0,0,0),nrow=3,ncol=3)
upperTriangle(z) <- t(lowerTriangle(z)[lowerTriangle(z)==1])

But this replace the entire upper triangle with 1. Any help with this would be greatly appreciated.

1
Try z+ t(z*(z==1)) - akrun

1 Answers

4
votes
z <- matrix(c(0,1,2,0,0,1,0,0,0),nrow=3,ncol=3)
z[upper.tri(z) & t(z) == 1] = 1

works for me.

Note: your upperTriangel and lowerTriangle do not appear to be part of base. You might want to indicate which package they are from.