计算一个向量的值在另一个向量中的出现次数 [英] Count the occurrence of one vector's values in another vector

查看:33
本文介绍了计算一个向量的值在另一个向量中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个向量

v1 <- c(164,38,20,19,163,22,21,4) 
v2 <- c(0,21,164,60,59,58,57,22,5,3,164,38,22,20,4,164,38,20,19,3,4,19,20,164,21,3,4,19,22,20,164,163,20,19,3)

我想计算向量 2 中向量 1 中数字的出现次数.我试图用循环来做,但由于表格的格式,它并没有完全奏效.

I would like to count the occurrence of the numbers in vector 1 in vector 2. I tried to do it with a loop but it didn't quite worked because of the format of the table.

a<-table(v2)
occurrence<-numeric()
for(i in v1){
   occurrence[i]<-a[names(a)==v1[i]]
}
occurSum<-sum(occurrence)

你知道一种最好不使用循环的方法吗?

Do you know a way to do this preferably without using a loop?

推荐答案

也许你正在寻找类似于 table%in% 的组合:

Perhaps you are looking for something like a combination of table and %in%:

> table(v2[v2 %in% v1])

  4  19  20  21  22  38 163 164 
  3   4   5   2   3   2   1   5 

或者,在您尝试的基础上,您可以尝试:

Or, building on your attempt, you might try:

tv2 <- table(v2)
tv2[match(v1, names(tv2))]

这篇关于计算一个向量的值在另一个向量中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆