rmatrix

Convert a matrix in R into a upper triangular/lower triangular matrix with those corresponding entries


I have a symmetric matrix and I want to convert it into a upper triangular/lower triangular matrix in R. Is there a way of doing this ?

I am not able to do this using upper.tri and lower.tri. Using these gives me a matrix with entries as either TRUE or FALSE.


Solution

  • To get the upper triangular matrix:

    mat <- matrix(1:9, 3, 3)
    mat[lower.tri(mat)] <- 0
    

    To remove diagonal, use:

    mat[lower.tri(mat,diag=TRUE)] <- 0 or mat[!upper.tri(mat)] <- 0 as suggested in the comments by Karolis.