Count occurrences of elements in a vector that occur in another vector

Viewed 121

I'm trying to count the occurrences of the elements in a vector that occur in another vector.

v1 <- c(1,2,3)
v2 <- c(1,1,1,2,2,2)

How many times do 1,2,3 occur in v2? desired result 3,3,0

This, tabulate(match(v2, v1)), returns

3,3
3 Answers

Yet another option could be:

colSums(sapply(v1, `==`, v2))

[1] 3 3 0

We can use factor with levels set as 'v1' and then use table or tabulate

table(factor(v2, levels = v1))
# 1 2 3 
# 3 3 0 

Or

tabulate(factor(v2, levels = v1), length(v1))
#[1] 3 3 0

Or in this case

tabulate(v2, length(v1))
#[1] 3 3 0

I think the approach by @akrun is the easiest. Here is another option but not that simple

> sapply(setNames(v1,v1),function(x) sum(v2 %in% x))
1 2 3
3 3 0
Related