# How to create a subset of rows or columns of a matrix in R?

A matrix can have multiple rows and columns like a data frame. As in data frames, we sometimes require to take subsets, the same might be required with matrices. But subsetting matrices data is quite simple as compared to subsetting a data frame.

## Example

Consider the below matrix −

> M<-matrix(1:25,5)
> M
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25

Subsetting columns of matrix M −

> M[,1,drop=FALSE]
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
> M[,3,drop=FALSE]
[,1]
[1,] 11
[2,] 12
[3,] 13
[4,] 14
[5,] 15
> M[,5,drop=FALSE]
[,1]
[1,] 21
[2,] 22
[3,] 23
[4,] 24
[5,] 25

Subsetting rows of matrix M −

> M[1,,drop=FALSE]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
> M[3,,drop=FALSE]
[,1] [,2] [,3] [,4] [,5]
[1,] 3 8 13 18 23
> M[5,,drop=FALSE]
[,1] [,2] [,3] [,4] [,5]
[1,] 5 10 15 20 25

Create a new matrix with column names and row names as shown below −

> M_new<-matrix(c(25,23,25,20,15,17,13,19,25,24,21,19,20,12,30,17),ncol=4)
> M_new
[,1] [,2] [,3] [,4]
[1,] 25 15 25 20
[2,] 23 17 24 12
[3,] 25 13 21 30
[4,] 20 19 19 17
> colnames(M_new)<-c("C1","C2","C3","C4")
> rownames(M_new)<-c("R1","R2","R3","R4")
> M_new
C1 C2 C3 C4
R1 25 15 25 20
R2 23 17 24 12
R3 25 13 21 30
R4 20 19 19 17

Subsetting columns and rows of M_new −

> M_new[,1,drop=FALSE]
C1
R1 25
R2 23
R3 25
R4 20
> M_new[,3,drop=FALSE]
C3
R1 25
R2 24
R3 21
R4 19
> M_new[1,,drop=FALSE]
C1 C2 C3 C4
R1 25 15 25 20
> M_new[4,,drop=FALSE]
C1 C2 C3 C4
R4 20 19 19 17

Updated on: 10-Aug-2020

1K+ Views