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

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

A simple way:

lower.triangle(X) #lower triangular

upper.triangle(X) #upper triangular

Or:

library(Matrix)

tril(X) #lower triangular

triu(X) #upper triangular

Tags:

Matrix

R