本文介绍了一一计算向量中多个数字的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个向量
a <- c(1, 5, 2, 1, 2, 3, 3, 4, 5, 1, 2) b <- (1, 2, 3, 4, 5, 6)我想知道b中每个元素在a中出现多少次。因此结果应为
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)我发现的所有方法,例如 match(), == ,%in%等不适用于整个向量。我知道我可以对b中的所有元素使用循环,
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) },但是它经常使用并且花费很长时间。这就是为什么我在寻找矢量化方法或使用 apply()的方法。
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().
推荐答案您可以使用 factor 和 table
table(factor(a, unique(b))) # #1 2 3 4 5 6 #3 3 2 1 2 0
自从您提到 match ,这是没有 sapply 循环的可能性(感谢@thelatemail)
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更多推荐
一一计算向量中多个数字的出现
发布评论