- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 subset a matrix in R by ignoring a value in one of the columns?
To subset a matrix in R by ignoring a value in one of the columns, we can follow the below steps −
First of all, create a matrix.
Then, use single square brackets to subset the matrix by ignoring a value in one of the columns.
Example
Create the matrix
Let’s create a matrix as shown below −
M<-matrix(rpois(100,5),ncol=4) M
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [,3] [,4] [1,] 7 8 6 6 [2,] 4 5 2 7 [3,] 6 4 7 4 [4,] 3 8 6 2 [5,] 5 8 4 7 [6,] 4 7 3 2 [7,] 7 4 7 6 [8,] 1 8 7 5 [9,] 3 4 3 3 [10,] 5 3 3 2 [11,] 1 6 7 6 [12,] 9 2 4 0 [13,] 4 4 1 6 [14,] 8 9 5 6 [15,] 6 5 8 1 [16,] 5 6 5 6 [17,] 2 4 5 5 [18,] 4 8 6 7 [19,] 4 11 8 4 [20,] 4 4 10 9 [21,] 5 6 6 4 [22,] 4 2 6 5 [23,] 6 8 6 6 [24,] 5 6 3 3 [25,] 6 6 6 3
Subset the matrix by ignoring a value in one of the columns
Using single square brackets to subset the matrix M by ignoring 4 in column 1 as shown below −
M<-matrix(rpois(100,5),ncol=4) M[M[,1]!=4,]
Output
[,1] [,2] [,3] [,4] [1,] 7 8 6 6 [2,] 6 4 7 4 [3,] 3 8 6 2 [4,] 5 8 4 7 [5,] 7 4 7 6 [6,] 1 8 7 5 [7,] 3 4 3 3 [8,] 5 3 3 2 [9,] 1 6 7 6 [10,] 9 2 4 0 [11,] 8 9 5 6 [12,] 6 5 8 1 [13,] 5 6 5 6 [14,] 2 4 5 5 [15,] 5 6 6 4 [16,] 6 8 6 6 [17,] 5 6 3 3 [18,] 6 6 6 3
Advertisements