RTrain3k
RTrain3k

Reputation: 867

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

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

Upvotes: 3

Views: 1056

Answers (3)

tmfmnk
tmfmnk

Reputation: 39858

Yet another option could be:

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

[1] 3 3 0

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

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

Upvotes: 0

akrun
akrun

Reputation: 886938

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

Upvotes: 0

Related Questions