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

前端 未结 2 455
野的像风
野的像风 2020-12-21 18:00

My question:

Amat <- diag(4)

I would like to replace all the lower triangular values of Amat (i.e. Amat[2,1],

相关标签:
2条回答
  • 2020-12-21 18:13

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

    These functions are in R base.

    0 讨论(0)
  • 2020-12-21 18:27

    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.

    0 讨论(0)
提交回复
热议问题