I need to find the common elements in vectors a & b and make a new vector c which contains these common elements, and afterward count the number of elements in c (i.e the number of common elements which in this case would be 1).
Asked
Active
Viewed 2,900 times
4
-
2intersect() and length(). consider not to call "c" the result, otherwise you are overwriting function c(). – marc1s Mar 08 '20 at 20:54
2 Answers
6
Is this what you are looking for?
a <- LETTERS[c(1:5, 10:15)]
b <- LETTERS[1:10]
intersect(a,b)
[1] "A" "B" "C" "D" "E" "J"
length(intersect(a,b))
[1] 6

Chris Ruehlemann
- 20,321
- 4
- 12
- 34
1
- If you want to keep the duplicates of common elements in both
a
andb
, you can usevintersect
from package, i.e.,
vecsets::vintersect(a,b)
# [1] "A" "A" "B" "B" "C" "D" "E"
- otherwise,
intersect
from base R will give you unique common elemtns, i.e.,
intersect(a,b)
# [1] "A" "B" "C" "D" "E"
DATA
a <- c("A", "B", "C", "D", "E", "A", "B", "C", "D", "E")
b <- c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "A", "B")

ThomasIsCoding
- 96,636
- 9
- 24
- 81