R语言 比较两个字符向量
在这篇文章中,我们将讨论如何在R编程语言中比较两个字符向量。
方法1:使用%in%
该操作符用于查找一个向量中存在的元素与第二个向量的关系
语法: vector1 %in% vector2
返回类型: 它返回与向量中的元素相对应的布尔值
- 如果相应的元素存在于向量2中,则返回 true 。
- 如果相应的元素不存在于向量2中,则返回 false 。
例子
# create a vector named names
# of college 1
names1 = c("mohan","sravya","navya")
# create a vector named names
# of college 2
names2 = c("mohan","sravan","deepika")
# check names1 is present in
# names 2
print(names1 %in% names2)
输出
[1] TRUE FALSE FALSE
方法2:使用 intersect( )函数
intersect()函数用于返回两个向量中存在的共同元素。因此,两个向量进行比较,如果存在共同元素,则显示出来。
语法
intersect(vector1,vector2)
例子
# create a vector named names
# of college 1
names1 = c("mohan","sravya","navya")
# create a vector named names
# of college 2
names2 = c("mohan","sravan","deepika")
# find the common elements
print(intersect(names1,names2))
输出
[1] "mohan"
方法3:使用 setdiff( )
该函数返回存在于向量1中但不存在于向量2中的元素,反之亦然。因此,首先比较两个向量的相似性,并相应显示元素。
语法
setdiff(vector1,vector2)
例子
# create a vector named names
# of college 1
names1 = c("mohan","sravya","navya")
# create a vector named names
# of college 2
names2 = c("mohan","sravan","deepika")
# find the set difference in the
# elements
print(setdiff(names1,names2))
# find the set difference in the
# elements
print(setdiff(names2,names1))
输出
[1] "sravya" "navya"
[1] "sravan" "deepika"