rmatrixdiagonal

Oneliner in R to replace upper triangle of a matrix with its lower triangle?


How to copy the lower triangle of a matrix to the upper triangle of that same matrix?

mat <- t(lower.tri(mat) * mat) + lower.tri(mat) * mat

...does not keep the diagonal (I know it shouldn't.).

I can save the diagonal to a separate variable before the operation and bring it back after the operation. But this feels so clumsy:

diag_mat <- diag(mat)
mat <- t(lower.tri(mat) * mat) + lower.tri(mat) * mat
diag(mat) <- diag_mat

Any ideas how to do this as a oneliner?


Solution

  • Like so:

    mat <- matrix(1:9, nrow = 3)
    #      [,1] [,2] [,3]
    # [1,]    1    4    7
    # [2,]    2    5    8
    # [3,]    3    6    9
    
    mat[upper.tri(mat)] <- t(mat)[upper.tri(mat)]
    #      [,1] [,2] [,3]
    # [1,]    1    2    3
    # [2,]    2    5    6
    # [3,]    3    6    9