首页 > 解决方案 > 如何在R中找到不同长度的多个(6)向量之间唯一向量交集的所有可能组合

问题描述

我有一组 6 个不同长度的向量(列名:tp1-tp6)。看起来像这样:

    tp1     tp2     tp3     tp4     tp5     tp6
    K06167  K14521  K17095  K21805  K03238  K18213
    K07376  K17095  K01424  K13116  K03283  K14521
    K03347  K14521  K14319  K00799  K08901  K01756
    K20179  K01693  K01682  K03283  K02716  K03238
    K03527  K02882  K01414  K01693  K08907  K01850
    K08901  K02912  K00940  K14319  K00411  K01768
    K11481  K02868  K04043  K14835  K01414  K15335
    K02716  K14835  K12606  K19371  K00963  K12818
    K03545  K14766  K09550  K04043  K01749  K02975
    K08907  K00602  K15437  K09550  K03116  K03002
    K15470  K10798  K03456  K03687  K09550  K17679
    K16465  K14823  K18059  K03456  K08738  K13116
    K03116  K00940  K03115  K18534  K08907  K14521
    K08738  K16474  K15502  K03495  K03687  K01937
    K08907  K19371  K00026  K13100  K08907  K03002
    .
    .
    .

我想创建一个列表,其中包含在 6 个向量的每个可能组合之间匹配的所有相应 K 值。例如,对于 tp2 和 tp3 的组合,我想找到两个向量共有的所有值,但不会出现在任何其他向量(tp1、tp4、tp5、tp6)中。在这种情况下,它将是 K00940。这可能在 R 中使用不同长度的向量吗?

有一个类似的问题被问到

找到所有可能的向量交集组合?

我已经尝试了答案中给出的代码之一。虽然代码确实在一个大列表中为我提供了所有可能的组合及其各自的值,但它并没有考虑到我只想要不同向量之间的唯一交集。例如,tp2 和 tp3 的组合产生了两个向量共有的所有可能值,但包括存在于其他向量中的值,这些值也存在于 tp2 和 tp3 中。我只想要只有 tp2 和 tp3 共有的唯一值。

veclist <- list(tp1, tp2, tp3, tp4, tp5, tp6) 

combos <- Reduce(c,lapply(1:length(veclist), function(x) combn(1:length(veclist),x,simplify=FALSE)))

CKUP_combos <- lapply(combos, function(x) Reduce(intersect, veclist[x]) )

标签: rcombinationscombn

解决方案


sel = function(x)
{
  sh = names(veclist)%in%names(x)
  a = setdiff(Reduce(intersect,veclist[sh]),unlist(veclist[!sh]))
 if (length(a)>0) setNames(list(a),toString(names(x)))
}

res = Map(combn,list(veclist),1:6,c(sel),simplify=F)
unlist(unlist(res,FALSE),FALSE)

推荐阅读