Count occurence of multiple numbers in vector one

2019-03-02 11:58发布

问题:

I have two vectors

a <- c(1, 5, 2, 1, 2, 3, 3, 4, 5, 1, 2)
b <- (1, 2, 3, 4, 5, 6)

I want to know how many times each element in b occurs in a. So the result should be

c(3, 3, 2, 1, 2, 0)

All methods I found like match(),==, %in% etc. are not suited for entire vectors. I know I can use a loop over all elements in b,

for (i in 1:length(b)) {
    c[I] <- sum(a==b, na.rm=TRUE)
}

but this is used often and takes to long. That's why I'm looking for a vectorized way, or a way to use apply().

回答1:

You can do this using factor and table

table(factor(a, unique(b)))
#
#1 2 3 4 5 6
#3 3 2 1 2 0

Since you mentioned match, here is a possibility without sapply loop (thanks to @thelatemail)

table(factor(match(a, b), unique(b)))
#
#1 2 3 4 5 6
#3 3 2 1 2 0


回答2:

Here is a base R option, using sapply with which:

a <- c(1, 5, 2, 1, 2, 3, 3, 4, 5, 1, 2)
b <- c(1, 2, 3, 4, 5, 6)

sapply(b, function(x) length(which(a == x)))
[1] 3 3 2 1 2 0

Demo



回答3:

Here is a vectorised method

x = expand.grid(b,a)
rowSums( matrix(x$Var1 == x$Var2, nrow = length(b)))
# [1] 3 3 2 1 2 0


标签: r counting