
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Subset a Matrix Based on Column Values in R
To subset a matrix based on values in a particular column, we can use single square brackets and provide the row and column values. The column values will be set for the columns that we want to subset and the row value will be set for the values of the column using which we want to subset the matrix.
Check out the below example to understand how it works.
Example
Following snippet creates a matrix −
M<-matrix(rpois(80,5),ncol=4) M
The following matrix is created −
[,1] [,2][,3][,4] [1,] 8 4 6 3 [2,] 5 6 1 8 [3,] 5 4 7 5 [4,] 3 9 1 6 [5,] 6 4 3 5 [6,] 3 4 3 5 [7,] 7 6 5 6 [8,] 7 5 7 1 [9,] 9 6 9 6 [10,] 5 4 5 5 [11,] 5 8 4 4 [12,] 3 2 7 4 [13,] 4 3 1 6 [14,] 1 4 4 5 [15,] 4 7 5 4 [16,] 5 2 6 4 [17,] 5 6 3 5 [18,] 8 8 3 6 [19,] 8 5 4 6 [20,] 2 5 6 3
To subset a matrix based on values in a particular column, add the following code to the above snippet −
M[,4]<-rep(c(1,2,3,4),times=5) M
If you execute the above given snippet, it generates the following output −
[,1][,2][,3][,4] [1,] 8 4 6 1 [2,] 5 6 1 2 [3,] 5 4 7 3 [4,] 3 9 1 4 [5,] 6 4 3 1 [6,] 3 4 3 2 [7,] 7 6 5 3 [8,] 7 5 7 4 [9,] 9 6 9 1 [10,] 5 4 5 2 [11,] 5 8 4 3 [12,] 3 2 7 4 [13,] 4 3 1 1 [14,] 1 4 4 2 [15,] 4 7 5 3 [16,] 5 2 6 4 [17,] 5 6 3 1 [18,] 8 8 3 2 [19,] 8 5 4 3 [20,] 2 5 6 4
To subset a matrix based on values in a particular column, add the following code to the above snippet −
M[M[,4]==1,c(1:3)]
If you execute the above given snippet, it generates the following output −
[,1][,2][,3] [1,] 8 4 6 [2,] 6 4 3 [3,] 9 6 9 [4,] 4 3 1 [5,] 5 6 3
To subset a matrix based on values in a particular column, add the following code to the above snippet −
M[M[,4]==2,c(1:3)]
If you execute the above given snippet, it generates the following output −
[,1][,2][,3] [1,] 5 6 1 [2,] 3 4 3 [3,] 5 4 5 [4,] 1 4 4 [5,] 8 8 3
To subset a matrix based on values in a particular column, add the following code to the above snippet −
M[M[,4]==3,c(1:3)]
If you execute the above given snippet, it generates the following output −
[,1][,2][,3] [1,] 5 4 7 [2,] 7 6 5 [3,] 5 8 4 [4,] 4 7 5 [5,] 8 5 4
To subset a matrix based on values in a particular column, add the following code to the above snippet −
M[M[,4]==4,c(1:3)]
If you execute the above given snippet, it generates the following output −
[,1][,2][,3] [1,] 3 9 1 [2,] 7 5 7 [3,] 3 2 7 [4,] 5 2 6 [5,] 2 5 6