5

有没有一种简单的方法可以提取 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()了,但它似乎没有任何选择..

4

3 回答 3

7

1)方阵的i第-个偏移反向对角线m

off.rev.diag <- function(m, i = 0) m[ (row(m) + col(m) - 1) %% ncol(m) == i ]

例如:

> m <- matrix(1:25, 5); 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
> off.rev.diag(m, 1)
[1]  1 10 14 18 22
> off.rev.diag(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, 1) <- -(1:5)
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]   -1    6   11   16   21
[2,]    2    7   12   17   -5
[3,]    3    8   13   -4   23
[4,]    4    9   -3   19   24
[5,]    5   -2   15   20   25
于 2013-05-21T14:45:22.317 回答
5

您可以手动执行此操作,并使用一些按向量索引的技巧:

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
于 2013-05-21T14:38:50.290 回答
2

您可以在列倒置的矩阵上调用对角线,例如:

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
于 2016-09-15T12:54:28.437 回答