- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- How to create a subset of a matrix in R using row names?
- How to shuffle columns or rows of matrix in PyTorch?
- How to subset a matrix in R by ignoring a value in one of the columns?
- How to create a subset of matrix in R using greater than or less than a certain value of a column?
- How to multiply a matrix columns and rows with the same matrix rows and columns in R?
- How to randomize rows of a matrix in R?
- How to divide matrix rows by number of columns in R?
- How to create a subset of an R data frame based on multiple columns?
- How to create a matrix with equal rows in R?
- How to subset a matrix in R by specifying columns that contains NA?
- How to find the sum of rows, columns, and total in a matrix in R?
- Python Pandas - Select a subset of rows and columns combined
- How to find the mean of columns of an R data frame or a matrix?
- How to delete different rows and columns of a matrix using a single line code in R?
- Python – Create a Subset of columns using filter()

Advertisements