2

May be this is too simple of a question but I couldn't find a functional answer. How can we extract the opposite diagonal elements of any square matrix in R? In the example below that would be: 7, 2, 8.

r <- matrix(c(1, 5, 8, 1:3, 7:9), 3)
jay.sf
  • 60,139
  • 8
  • 53
  • 110

4 Answers4

4
diag(r[,rev(sequence(NCOL(r)))])
#OR
rev(r[row(r) == NCOL(r) - col(r) + 1])
#OR
rev(r[(row(r) + col(r)) == (nrow(r) + 1)])
#[1] 7 2 8
d.b
  • 32,245
  • 6
  • 36
  • 77
4

An approach could be

r[(n<-nrow(r))^2-(1:n)*(n-1)]
# [1] 7 2 8

## microbenchmark (matrix(1:1e6,1000))
# Unit: microseconds
#         expr       min         lq        mean    median         uq      max neval
#  r[(n<-nr...    26.897    39.0075    65.36835    47.309    85.9345   316.97   100
#  diag(r[,... 18070.388 18905.3475 20237.09599 19956.615 20423.4695 27798.88   100
#  rev(r[ro... 14220.609 21206.7220 21238.59515 22036.275 22599.4490 33252.58   100
jay.sf
  • 60,139
  • 8
  • 53
  • 110
1

We can also generate an index to extract those elements

n <- nrow(r)
r[seq(n, by = n-1, length = n)]
#[1] 8 2 7

If the order is important we can reverse the extracted elements.

rev(r[seq(n, by = n-1, length = n)])
#[1] 7 2 8
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • [This question](https://stackoverflow.com/questions/58309964/separate-columns-with-constant-numbers-and-condense-them-into-one-row-in-r-data) may be interesting to you? –  Oct 09 '19 at 18:16
1

You can use matrix subsetting like:

r[matrix(c(1:nrow(r), ncol(r):1), ncol=2)]
#[1] 7 2 8

or vector subsetting like

r[1:nrow(r) + (ncol(r):1-1)*nrow(r)]
#[1] 7 2 8
GKi
  • 37,245
  • 2
  • 26
  • 48