实现这一目标的一种快速方法是使用经常被忽视的方法,而无需以编程方式计算索引。row()
and col()
功能。对于矩阵的每个元素,它们分别返回该元素所属的行或列。
对角线是元素的行索引等于列索引的位置。第一个下对角线是行索引等于列索引的位置plus 1而第一个上对角线是行索引等于列索引的位置minus 1.
这里有些例子:
m <- matrix(1:25, ncol = 5)
m
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
对角线
m[row(m) == col(m)]
diag(m)
> m[row(m) == col(m)]
[1] 1 7 13 19 25
> diag(m) ## just to show this is correct
[1] 1 7 13 19 25
第一个下对角线
m[row(m) == col(m) + 1
> m[row(m) == col(m) + 1]
[1] 2 8 14 20
第一条上对角线
m[row(m) == col(m) -1]
> m[row(m) == col(m) -1]
[1] 6 12 18 24
可以通过增加列索引的添加值来提取高阶上对角线和下对角线。
创建数据框并写出
本质上你已经有了这个,但是
write.csv(data.frame(m[row(m) == col(m) + 1), file = "subdiag.csv")
下对角线或上对角线的一般函数
diags <- function(m, type = c("sub", "super"), offset = 1) {
type <- match.arg(type)
FUN <-
if(isTRUE(all.equal(type, "sub")))
`+`
else
`-`
m[row(m) == FUN(col(m), offset)]
}
在使用中我们有:
> diags(m)
[1] 2 8 14 20
> diags(m, type = "super")
[1] 6 12 18 24
> diags(m, offset = 2)
[1] 3 9 15