我有一组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中不同长度的向量,这是可能的吗?
也有类似的问题被问到
Finding all possible combinations of vector intersections?
我试过答案中给出的一个代码。虽然代码确实在一个大列表中给出了所有可能的组合和它们各自的值,但它没有考虑到我只想要不同向量之间的唯一交集。例如,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]) )发布于 2019-09-26 05:57:36
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)发布于 2019-09-26 06:52:58
定义以下函数:
getUniqueIntersections <- function(veclist, col1name, col2name){
#Returns vector of all strings in components col1name and col2name of veclist
# that are not in any of the other components of veclist.
inc1 <- veclist[[col1name]]
inc2 <- veclist[[col2name]]
inc <- intersect(inc1, inc2)
excNames <- setdiff(names(veclist), c(col1name, col2name))
exc <- unique(do.call(c, veclist[excNames]))
result <- setdiff(inc, exc)
return(result)
}接下来,将veclist定义为感兴趣的向量的命名列表,然后使用这些名称创建我们想要遍历的对的数据帧:
veclist <- list(tp1=tp1, tp2=tp2, tp3=tp3, tp4=tp4, tp5=tp5, tp6=tp6)
dfCombNames <- as.data.frame(combn(names(veclist), 2))
dfCombNames
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15
#1 tp1 tp1 tp1 tp1 tp1 tp2 tp2 tp2 tp2 tp3 tp3 tp3 tp4 tp4 tp5
#2 tp2 tp3 tp4 tp5 tp6 tp3 tp4 tp5 tp6 tp4 tp5 tp6 tp5 tp6 tp6最后,通过遍历dfCombNames中的每一列来创建结果列表。
将tp3"
getUniqueIntersections中每一列的resultList <- list()
for(col in dfCombNames){
col1 <- as.character(col[1])
col2 <- as.character(col[2])
compName <- paste(as.character(col), collapse=",")
resultList[[compName]] <- getUniqueIntersections(veclist, col1, col2)
}resultList应包含所需的值,例如,
> resultList[["tp2,tp3"]]
[1] "K17095" "K00940"
> resultList[["tp1,tp5"]]
[1] "K08901" "K02716" "K08907" "K03116" "K08738"https://stackoverflow.com/questions/58106465
复制相似问题