Compare two character vectors in R
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
# create a vector named names# of college 1names1 = c("mohan","sravya","navya") # create a vector named names # of college 2names2 = c("mohan","sravan","deepika") # check names1 is present in # names 2print(names1 %in% names2) |
Output:
[1] TRUE FALSE FALSE
Method 2: Using intersect()
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
# create a vector named names # of college 1names1 = c("mohan","sravya","navya") # create a vector named names # of college 2names2 = c("mohan","sravan","deepika") # find the common elementsprint(intersect(names1,names2)) |
Output:
[1] "mohan"
Method 3: Using setdiff()
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
# create a vector named names # of college 1names1 = c("mohan","sravya","navya") # create a vector named names # of college 2names2 = c("mohan","sravan","deepika") # find the set difference in the # elementsprint(setdiff(names1,names2)) # find the set difference in the # elementsprint(setdiff(names2,names1)) |
Output:
[1] "sravya" "navya" [1] "sravan" "deepika"


