mat = matrix(c(1:25), nrow = 5, ncol = 5, byrow = TRUE)
mat
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
[4,] 16 17 18 19 20
[5,] 21 22 23 24 25
# Diagonal
mat[row(mat) == col(mat)]
[1] 1 7 13 19 25
# "Lower" diagonals
mat[row(mat) == col(mat)+1]
[1] 6 12 18 24
> mat[row(mat) == col(mat)+2]
[1] 11 17 23
# "Upper" diagonals
mat[row(mat) == col(mat)-1]
[1] 2 8 14 20
mat[row(mat) == col(mat)-2]
[1] 3 9 15
... but @BenBolker's answer is (of course) more elegant.
It looks like Ben deleted his answer, so I'll post a slight modification of it here. Assuming k
is the number of places above the main diagonal, then:
mat[col(mat) - row(mat) == k]
will give you the diagonal k
places above the main diagonal if k
is positive and below if k
is negative.
Per @MichaelChirico's comment, to get the "up-to-the-right" diagonals:
mat[row(mat) + col(mat) == m]
where 2 <= m <= 2*nrow(mat).