Count occurence of multiple numbers in vector one by one

拟墨画扇 提交于 2019-12-02 11:48:28

问题


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


来源:https://stackoverflow.com/questions/50980513/count-occurence-of-multiple-numbers-in-vector-one-by-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!