Compare two character vectors in R
Last Updated :
09 May, 2021
In this article, we will discuss how to compare two character vectors in R Programming Language.
Method 1: Using %in%
This operator is used to find the elements present in one vector with respect to the second vector
Syntax: vector1 %in% vector2
Return type: It returns boolean values corresponding to the elements in a vector
- It returns true, if corresponding element is present in vector 2
- It returns false, if corresponding element is not present in vector 2.
Example:
R
names1 = c ( "mohan" , "sravya" , "navya" )
names2 = c ( "mohan" , "sravan" , "deepika" )
print (names1 % in % names2)
|
Output:
[1] TRUE FALSE FALSE
intersect() function is used to return the common element present in two vectors. Thus, the two vectors are compared, and if a common element exists it is displayed.
Syntax:
intersect(vector1,vector2)
Example:
R
names1 = c ( "mohan" , "sravya" , "navya" )
names2 = c ( "mohan" , "sravan" , "deepika" )
print ( intersect (names1,names2))
|
Output:
[1] "mohan"
This function returns the elements present in vector1 but not present in vector2 and vice versa. Thus, two vectors are first compared for similarity, and elements are displayed accordingly.
Syntax:
setdiff(vector1,vector2)
Example:
R
names1 = c ( "mohan" , "sravya" , "navya" )
names2 = c ( "mohan" , "sravan" , "deepika" )
print ( setdiff (names1,names2))
print ( setdiff (names2,names1))
|
Output:
[1] "sravya" "navya"
[1] "sravan" "deepika"
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...