一一计算向量中多个数字的出现

编程入门 行业动态 更新时间:2024-10-10 01:22:33
本文介绍了一一计算向量中多个数字的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个向量

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

更多推荐

一一计算向量中多个数字的出现

本文发布于:2023-11-29 10:05:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646092.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   向量   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!