jenswirf jenswirf - 2 months ago 11
R Question

How to find offset diagonal of a matrix?

Is there an easy way to extract a vector of an 'offset' and 'reverse' "diagonal" (the x's) of a matrix in R?

[,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


I tried
diag()
but it does'nt seem to take any options..

Answer

1) The i-th offset reverse diagonal of square matrix m:

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

For example:

> 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) We can also write a replacement function:

"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)
}

For example,

> 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
Comments