Extract Vector Using Different Index for Columns in an R Matrix



Suppose we have a matrix and a vector containing indices of equal size as the matrix then we can extract the vector from matrix using the index vector. For this purpose, we can use cbind function as shown in the below examples.

Example1

Live Demo

> M1<-matrix(rpois(40,2),ncol=2)
> M1

Output

      [,1] [,2]
 [1,]    4    0
 [2,]    1    1
 [3,]    1    2
 [4,]    2    0
 [5,]    3    2
 [6,]    2    2
 [7,]    1    6
 [8,]    1    2
 [9,]    3    1
[10,]    1    2
[11,]    2    3
[12,]    2    0
[13,]    3    0
[14,]    0    1
[15,]    2    4
[16,]    1    1
[17,]    3    1
[18,]    0    2
[19,]    2    1
[20,]    2    0

Example

> Index_M1<-sample(1:2,20,replace=TRUE)
> Index_M1

Output

[1] 2 1 2 1 2 2 1 1 2 1 1 2 1 1 1 1 2 2 1 1

Example

> M1[cbind(seq_along(Index_M1),Index_M1)]

Output

[1] 0 1 2 2 2 2 1 1 1 1 2 0 3 0 2 1 1 2 2 2

Example2

Live Demo

> M2<-matrix(rpois(80,10),ncol=4)
> M2

Output

      [,1] [,2] [,3] [,4]
 [1,]   10    9    9   11
 [2,]   13    6   16    8
 [3,]   11   11    8   10
 [4,]   15   11    9    9
 [5,]   10    8    9    9
 [6,]    7   14    9   15
 [7,]    8    6    8    7
 [8,]    4    8    9   12
 [9,]    7   12   11   10
[10,]    8    8    9   13
[11,]    9   13   11    6
[12,]   12    5   11    8
[13,]    8    6   15    8
[14,]    6   17   12    7
[15,]    8   10    9    8
[16,]   13    7   11   13
[17,]    5   10    7    7
[18,]   10   11    8    8
[19,]    5    9    9   13
[20,]    5   10    7    6

Example

> Index_M2<-sample(1:4,20,replace=TRUE)
> Index_M2

Output

[1] 3 4 3 3 3 1 3 4 4 3 1 4 3 4 4 1 2 1 1 2

Example

> M2[cbind(seq_along(Index_M2),Index_M2)]

Output

[1] 9 8 8 9 9 7 8 12 10 9 9 8 15 7 8 13 10 10 5 10
Updated on: 2021-03-06T05:03:52+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements