-1

I want to form a vector from some specific elements of matrix (or dataframe).

I would like to create vector from for example minor diagonal elements from this matrix (e.g elements matrix[3,1], matrix[2,2] and matrix [1,3]).

Matrix

How could I do it without looping? My task is quite big and I would like skip looping. Following command:

matrix[c(3, 2, 1), c(1, 2, 3)]

instead of vector c(3, 5, 7) gives me another matrix.

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57

3 Answers3

2

Either of these will do what you want:

x <- matrix(1:9, 3, 3)
x
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9
rc <- seq(ncol(x))
diag(x[rev(rc),])
# [1] 3 5 7
x[cbind(rev(rc), rc)]
# [1] 3 5 7
dcarlson
  • 10,936
  • 2
  • 15
  • 18
0

try this

mat <- matrix(1:9, nrow = 3, byrow = T)
diag(apply(mat,2,rev))
Pedro Alencar
  • 1,049
  • 7
  • 20
-1

Your matrix:

mymatrix <- matrix(data= c(1,2,3,4,5,6,7,8,9), nrow = 3, byrow = T)

#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    4    5    6
#[3,]    7    8    9

you can get the diagonal like this:

diag(mymatrix)
# [1] 1 5 9
Sandwichnick
  • 1,379
  • 6
  • 13