user1632895
user1632895

Reputation: 73

How to replace lower/upper triangular elements of a matrix?

My question:

Amat <- diag(4)

I would like to replace all the lower triangular values of Amat (i.e. Amat[2,1], Amat[3,1], Amat[3,2], and so on) with a value I choose (e.g. NA).

Obviously I do not want to replace each element one by one.

Could you show me the most efficient way to do it with a single command?

Upvotes: 3

Views: 9951

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

This is pretty well documented in the docs for upper.tri.

Amat[upper.tri(Amat)] <- NA
Amat
#      [,1] [,2] [,3] [,4]
# [1,]    1   NA   NA   NA
# [2,]    0    1   NA   NA
# [3,]    0    0    1   NA
# [4,]    0    0    0    1

Of course, Amat[lower.tri(Amat)] <- NA would do the same for converting the lower triangle to NAs.

Upvotes: 9

ptocquin
ptocquin

Reputation: 325

Are lower.tri and upper.tri what you are looking for ?

These functions are in R base.

Upvotes: 5

Related Questions