4

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).

Ishaan Bedi
  • 51
  • 1
  • 5
  • 2
    intersect() and length(). consider not to call "c" the result, otherwise you are overwriting function c(). – marc1s Mar 08 '20 at 20:54

2 Answers2

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 and b, you can use vintersect 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