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