- Trending Categories
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 check matrix values equality with a vector values in R?
If we have a vector called V that contains five values and a matrix say M that contains five columns and we want to check whether first value in the vector is present in the first column of each row in the matrix and so on for each value in the vector then we can use the below command −
t(t(M)==V)
Example 1
Consider the below matrix and vector −
M1<-matrix(rpois(40,1),ncol=2) M1
The following dataframe is created
[,1] [,2] [1,] 2 0 [2,] 0 2 [3,] 1 1 [4,] 0 3 [5,] 2 1 [6,] 2 1 [7,] 2 0 [8,] 0 4 [9,] 0 3 [10,] 1 3 [11,] 0 1 [12,] 4 1 [13,] 1 2 [14,] 1 1 [15,] 2 3 [16,] 3 1 [17,] 3 1 [18,] 0 2 [19,] 0 2 [20,] 0 0
To check whether values in V1 are present in each row of M1 on the above created data frame, add the following code to the above snippet −
M1<-matrix(rpois(40,1),ncol=2) V1<-c(0,2) t(t(M1)==V1)
Output
If you execute all the above given snippets as a single program, it generates the following Output −
[,1] [,2] [1,] FALSE FALSE [2,] TRUE TRUE [3,] FALSE FALSE [4,] TRUE FALSE [5,] FALSE FALSE [6,] FALSE FALSE [7,] FALSE FALSE [8,] TRUE FALSE [9,] TRUE FALSE [10,] FALSE FALSE [11,] TRUE FALSE [12,] FALSE FALSE [13,] FALSE TRUE [14,] FALSE FALSE [15,] FALSE FALSE [16,] FALSE FALSE [17,] FALSE FALSE [18,] TRUE TRUE [19,] TRUE TRUE [20,] TRUE FALSE
Example 2
Consider the below matrix and vector −
M2<-matrix(round(rnorm(40),1),ncol=2) M2
The following dataframe is created
[,1] [,2] [1,] 1.6 -0.8 [2,] 0.7 -0.7 [3,] 0.1 -1.1 [4,] 0.1 1.5 [5,] 0.9 0.3 [6,] 1.3 1.2 [7,] 0.7 -0.3 [8,] -0.8 -0.1 [9,] -0.5 -1.4 [10,] -0.3 1.0 [11,] 0.6 -1.3 [12,] -0.4 0.8 [13,] 0.0 0.8 [14,] 1.5 0.5 [15,] -0.3 -0.8 [16,] 1.0 -0.5 [17,] 1.9 -1.3 [18,] 1.7 -0.7 [19,] 2.7 0.4 [20,] 0.9 -0.5
To check whether values in V2 are present in each row of M2 on the above created data frame, add the following code to the above snippet −
M2<-matrix(round(rnorm(40),1),ncol=2) V2<-c(0.1,0.5) t(t(M2)==V2)
Output
If you execute all the above given snippets as a single program, it generates the following Output −
[,1] [,2] [1,] FALSE FALSE [2,] FALSE FALSE [3,] TRUE FALSE [4,] TRUE FALSE [5,] FALSE FALSE [6,] FALSE FALSE [7,] FALSE FALSE [8,] FALSE FALSE [9,] FALSE FALSE [10,] FALSE FALSE [11,] FALSE FALSE [12,] FALSE FALSE [13,] FALSE FALSE [14,] FALSE TRUE [15,] FALSE FALSE [16,] FALSE FALSE [17,] FALSE FALSE [18,] FALSE FALSE [19,] FALSE FALSE [20,] FALSE FALSE