R 如何求矩阵的偏移对角线?

R 如何求矩阵的偏移对角线?,r,R,有没有一种简单的方法可以提取R中矩阵的“偏移”和“反向”对角线(x)的向量 [,1] [,2] [,3] [,4] [,5] [1,] x 0 0 0 0 [2,] 0 0 0 0 x [3,] 0 0 0 x 0 [4,] 0 0 x 0 0 [5,] 0 x 0 0 0 我尝试了diag(),但它似乎没有任何选择。你可以通过一些按

有没有一种简单的方法可以提取R中矩阵的“偏移”和“反向”对角线(x)的向量

      [,1] [,2] [,3] [,4] [,5]
[1,]    x    0    0    0    0
[2,]    0    0    0    0    x
[3,]    0    0    0    x    0
[4,]    0    0    x    0    0
[5,]    0    x    0    0    0

我尝试了diag(),但它似乎没有任何选择。

你可以通过一些按向量索引的技巧手动完成:

offset.rev.diag <- function(x, nrow, ncol, offset=1) {
    diag(x, nrow, ncol)[rev(1:nrow), c((offset+1):ncol, 1:offset)]
}

> offset.rev.diag(1, 5, 5)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    0
[2,]    0    0    1    0    0
[3,]    0    1    0    0    0
[4,]    1    0    0    0    0
[5,]    0    0    0    0    1

> offset.rev.diag(1, 5, 5, 3)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    0    0    0
[2,]    1    0    0    0    0
[3,]    0    0    0    0    1
[4,]    0    0    0    1    0
[5,]    0    0    1    0    0
offset.rev.diag offset.rev.diag(1,5,5)
[,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    0
[2,]    0    0    1    0    0
[3,]    0    1    0    0    0
[4,]    1    0    0    0    0
[5,]    0    0    0    0    1
>偏移版本诊断(1,5,5,3)
[,1] [,2] [,3] [,4] [,5]
[1,]    0    1    0    0    0
[2,]    1    0    0    0    0
[3,]    0    0    0    0    1
[4,]    0    0    0    1    0
[5,]    0    0    1    0    0
1)方阵
m
i
-th偏移反向对角线

off.rev.diag <- function(m, i = 0) m[ (row(m) + col(m) - 1) %% ncol(m) == i ]
off.rev.diag m off.rev.diag(m,1)
[1]  1 10 14 18 22
>关闭版本诊断(m,2)
[1]  2  6 15 19 23
2) 我们还可以编写一个替换函数:

"off.rev.diag<-" <- function(m, i = 0, value) { 
    m.ix <- matrix(seq_along(m), nrow(m))
    replace(m, off.rev.diag(m.ix, i), value)
}

“off.rev.diag您可以在矩阵上调用对角线,并反转列,如:

m = matrix(1:16, ncol = 4L, nrow = 4L)
m
diag(m[,ncol(m):1])
#> m
#     [,1] [,2] [,3] [,4]
#[1,]    1    5    9   13
#[2,]    2    6   10   14
#[3,]    3    7   11   15
#[4,]    4    8   12   16
#> diag(m[,ncol(m):1])
#[1] 13 10  7  4
对于偏移量,只需删除与偏移量对应的行数和列数

diag(m[-nrow(m),-1])
#> diag(m[-nrow(m),-1])
#[1]  5 10 15
对于偏移辅助对角线,将两者合并

diag(m[-1, -1][3:1,])
#> diag(m[-1, -1][3:1,])
#[1]  8 11 14

该死!这让我完全糊涂了,直到我意识到运算符优先级意味着它是
m[((stuff)%%ncol(m))==1]
diag(m[-nrow(m),-1])
#> diag(m[-nrow(m),-1])
#[1]  5 10 15
diag(m[-1, -1][3:1,])
#> diag(m[-1, -1][3:1,])
#[1]  8 11 14