diag()可以取出矩阵对角线数据, 修改对角线数据, 生成指定对角线数值的矩阵等.
而利用 lower.tri 可以取出矩阵对角线下方的数值,
利用upper.tri 可以取出矩阵对角线上方的数值.
实际上这两个函数是将对角线两边的位置置为TRUE或FALSE.
例如 :
对角线上方为TRUE, 其他(含对角线)为FALSE
使用 x[upper.tri(x)]则可以取出这些TRUE的值.
对角线下方为TRUE, 其他(含对角线)为FALSE
使用 x[lower.tri(x)]则可以取出这些TRUE的值.
同时, 我们可以使用 x[lower.tri(x)] 来设置矩阵的这些值.
[参考]
> x
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
对角线上方为TRUE, 其他(含对角线)为FALSE
> upper.tri(x)
[,1] [,2] [,3] [,4]
[1,] FALSE TRUE TRUE TRUE
[2,] FALSE FALSE TRUE TRUE
[3,] FALSE FALSE FALSE TRUE
使用 x[upper.tri(x)]则可以取出这些TRUE的值.
> x[upper.tri(x)]
[1] 4 7 8 10 11 12
对角线下方为TRUE, 其他(含对角线)为FALSE
> lower.tri(x)
[,1] [,2] [,3] [,4]
[1,] FALSE FALSE FALSE FALSE
[2,] TRUE FALSE FALSE FALSE
[3,] TRUE TRUE FALSE FALSE
使用 x[lower.tri(x)]则可以取出这些TRUE的值.
> x[lower.tri(x)]
[1] 2 3 6
同时, 我们可以使用 x[lower.tri(x)] 来设置矩阵的这些值.
> x[lower.tri(x)] = c(1,1,1)
> x
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 1 5 8 11
[3,] 1 1 9 12
> x[lower.tri(x)] = 100
> x
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 100 5 8 11
[3,] 100 100 9 12
[参考]
> help("lower.tri")
lower.tri package:base R Documentation
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