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
.
Data Visualization using R Programming To create an upper triangular matrix using vector elements, we can first create the matrix with appropriate number of columns and rows then take the transpose of that matrix. After that we will assign the lower triangular matrix elements to 0.
In R, you create a triangular matrix with the lower. tri() function for a lower triangular matrix, or the upper. tri() function for the upper triangular matrix. Both functions require a square matrix as input.
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.
While the previous answer is perfect, the manual is your friend:
Lower and Upper Triangular Part of a Matrix
Description
Returns a matrix of logicals the same size of a given matrix with entries TRUE in the lower or upper triangle.
Usage
lower.tri(x, diag = FALSE) upper.tri(x, diag = FALSE)
Arguments
x
a matrix.
diag
logical. Should the diagonal be included?
See Also
diag, matrix.
Examples
(m2 <- matrix(1:20, 4, 5)) lower.tri(m2) m2[lower.tri(m2)] <- NA m2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With