-4

I have a question regarding compare elements in 2 vectors. For example, I have 2 vectors

a<-c(8, 28, 23, 21, 7, 3, 24, 6, 1, 4)
b<-c(28, 27, 8, 7, 6, 23, 21, 3, 1, 26)

Now I want to answer the question "How many elements in a are the same as element in b?"

Which mean that I have 1, 3, 6, 7, 8, 21, 23, 28 are common numbers --> 8 elements in common.

Do we have any function in R help me to answer this question? Thank you in advance.

crucialoil
  • 381
  • 1
  • 5
  • 17

1 Answers1

1

You can try intersect function

> intersect(a, b)
[1]  8 28 23 21  7  3  6  1

Edit: to get the count use length function

> length(intersect(a, b))
[1] 8
Nishanth
  • 6,932
  • 5
  • 26
  • 38
  • Thank you so much, Nishanth! It works for numbers, but can I ask what if my 2 vectors output look like: `[1] "V17" "V20" "V27" "V29" "V13" "V11" "V21" "V4" "V6" "V8"` and `[1] "V13" "V29" "V11" "V4" "V21" "V8" "V6" "V17" "V20" "V27"` – crucialoil Oct 13 '15 at 16:10