是否有一种简单的方法可以在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()
,但它似乎没有采取任何选择..
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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