Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

matrix

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.

like image 584
Anurag Mishra Avatar asked Oct 15 '14 07:10

Anurag Mishra


People also ask

How do you make a upper triangular matrix in R?

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.

How do you make a lower triangular matrix in R?

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.


2 Answers

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.

like image 117
Ujjwal Avatar answered Sep 25 '22 17:09

Ujjwal


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 
like image 31
serv-inc Avatar answered Sep 25 '22 17:09

serv-inc