0

I have the following matrix mat

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

and I'd like to extract the elements of [2,1] and [3,2]. In other words, I'd like the output to be 4 and 8.

> mat[[2,1], [3,2]] 

did not work (error) and

> mat[c(2,3), c(1,2)]
     [,1] [,2]
[1,]    4    5
[2,]    7    8

isn't correct either.

What is the right way of extracting 4 and 8 with one line of code?

I know I can extract them individually and then put them into the same vector, but that's not how I'd like to do it... I was wondering if there's a cleaner way.

Joehat
  • 979
  • 1
  • 9
  • 36

1 Answers1

3

You can cbind/rbind the positions to create a matrix which can be used to get values from mat.

mat <- matrix(1:9, nrow = 3, byrow = TRUE)
mat[cbind(c(2, 3), c(1, 2))]
#With rbind
#mat[rbind(c(2, 1), c(3, 2))]
#[1] 4 8
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213