r - 如何通过多数投票规则找到不同向量之间的共同成员
问题描述
我试图找到多个向量之间的共同元素。目前的情况有点棘手,公共元素不需要完全相同,但可能会有一些错误,比如 +/- 1,即使是公共元素也不需要在所有这些向量中显示,它们是由多数投票规则选出。此外,这些向量具有不同的长度。这是一个例子,
a <- c(5,7,11,18,27,30);
b <- c(5,8,18,26);
c <- c(6,7,10,26,30)
a中的5,b中的5,c中的6,将被视为公共元素,将取地板(平均值),即5;
a 中的 7,b 中的 8,c 中的 7,将被视为公共元素,将取地板(平均值),即 7;
a中的11,c中的10,将被视为公共元素,将取地板(平均值),即10;
相同的规则适用于 18,26,30
因此,我应该得到的最终结果是c(5,7,10,18,26,30)
解决方案
您可以通过移动窗口方法来做到这一点。首先我们可以将这些值组合成一个向量,然后我们使用大小为“多数”的移动窗口(在本例中为 2)。如果移动窗口中的值在误差范围内(在本例中为 1),则将最小值添加到我们的常用值列表中,然后删除这些值。然后继续检查值。
这是一个函数:
#vec_list -> list of the vectors to compare
#error -> margin of error to tolerate
#returns a vector of the common numbers
get_common_values = function(vec_list, error){
all = sort(unlist(vec_list)) #put all the numbers in one vector and sort them
majority = ceiling(length(vec_list)/2) #get the number of values that constitute a majority
common = c() #initialize an empty vector to store the values
#now we'll loop over 'all' and find common values - and we'll remove them as we go
#this is basically a moving window approach
while(length(all) >= majority){ #keep going until we've gone through all the elements
vals_i = all[1:majority] #get the values at the front
if(diff(range(vals_i)) <= error){ #if the range is <= to the error, then this value can be considered one of the 'common' values
new_val = min(vals_i) #get the minimum of the values
common = c(common, new_val) #add it to our vector of common values
all = all[!(all %in% new_val:(new_val+error))] #remove any of the values that fall within this range
} else {
all = all[2:length(all)] #if the range isn't greater than the error, just remove the first element
}
}
return(common)
}
我们可以这样使用它:
a = c(5,7,11,18,27,30)
b = c(5,8,18,26)
c = c(6,7,10,26,30)
get_common_values(list(a,b,c),1)
这返回5 7 10 18 26 30
。
它还适用于三个以上的向量,并且具有不同的容错性:
set.seed(0)
a = sample(1:100,8)
b = sample(1:100,10)
c = sample(1:100,7)
d = sample(1:100,11)
e = sample(1:100,9)
get_common_values(list(a,b,c,d,e),2)
请注意,这假设每个向量中没有重复项,根据您提供的信息,这似乎是一个有效的假设。
推荐阅读
- asp.net-mvc - 在 Task.Run 中调用异步方法
- excel - 如何在 EXCEL 中的活动行中选择一列以使用 VBA 粘贴到单独的工作表上?
- sqlite - 在调试 Xamarin Forms 应用程序时检查 SQLLite 数据库内容
- java - maven testng 项目 - 更改 testng.xml 后,当我从终端执行时它没有改变
- angular - 顺序订阅多个服务调用
- python - opencv:如何在单个深度图像中找到轮廓?
- git - 如何在没有退出代码 1 的情况下在 Sublime Merge 中创建新存储库?
- angular - CloudFront 源响应超时 > 60
- python - 无法在 ETL 过程中使用 Pandas 和 SQLAlchemy 将列名从 CSV 更改为 SQL Server DB
- bash - 如果和要删除的最后一个数字