R语言 如何从多个向量中找到共同元素
在这篇文章中,我们将讨论如何在R编程语言中从多个向量中找到共同元素。
要做到这一点,需要使用 intersect() 方法。它用于返回两个对象的共同元素。
语法: intersect(vector1,vector2)
其中, 向量是输入数据。
如果有两个以上的向量,那么我们可以将所有这些向量合并成一个,除了一个向量。这些合并的向量被作为一个参数传递,剩下的向量被作为第二个参数传递。
语法: intersect(c(vector1,vector2,…,vector n),vector_m)
例1: R程序创建两个向量并找出共同元素。
所以我们要创建一个有元素的向量。
# create vector b
b = c(2, 3, 4, 5, 6, 7)
# create vector a
a = c(1, 2, 3, 4)
# combine both the vectors
print(intersect(b, a))
输出 。
[1] 2 3 4
例子2: R程序寻找两个字符数据中的共同元素。
我们取两个包含名字的向量,并找出其中的共同元素。
# create vector b
b = c("sravan", "gajji", "gnanesh")
# create vector a
a = c("sravan", "ojaswi", "gnanesh")
# combine both the vectors
print(intersect(b, a))
输出 。
[1] "sravan" "gnanesh"
例3: 在R中从多个向量中寻找共同元素。
所以我们先把b和a结合起来,把它们作为intersect函数的第一个参数,然后把d向量作为第二个参数。
# create vector b
b = c(1, 2, 3, 4, 5)
# create vector a
a = c(3, 4, 5, 6, 7)
# create vector d
d = c(5, 6, 7, 8, 9)
# combine both the vectors b and a as 1
# then combine with d
print(intersect(c(b, a), d))
输出 。
[1] 5 6 7