1

我有一个包含几个向量的列表,例如:

ls=list(c("g1","g3","g6"),c("g1","g4"),c("g2","g5"),c("g2","g5"),c("g2"))

我想捕获最少数量的元素,以便每个向量中至少有一个元素。

所以在这个例子中,“g1”和“g2”,因为 g1 捕获向量 1 和 2,而 g2 捕获向量 1、3、4 和 5。

我一直在研究如何从多个向量中找到共同元素?但这不是同一个问题。

4

1 回答 1

1

蛮力:

ls <- list(c("g1","g3","g6"),c("g1","g4"),c("g2","g5"),c("g2","g5"),c("g2"))
#unique values:
vals <- unique(do.call(c,ls))
#matrix indicating in which list each value is present
valsin <- sapply(ls,function(x) as.integer(vals %in% x))
rownames(valsin) <- vals

#loop through numbers of values to take for combinations
for (i in seq_along(vals)) {

    cat(paste0(i,"\n"))
    #Do combinations fullfill condition?
    suff <- combn(seq_along(vals),i,FUN=function(x) {
      identical(colSums(valsin[x,,drop=FALSE]),rep(1,length(ls)))
    })
    if (sum(suff) > 0) {
      #combinations that fullfill condition
      res <- combn(vals,i)[,suff]
      #stop loop if condition has been fullfilled
      break
    }

}

res
#[1] "g1" "g2"
于 2013-04-26T13:50:00.123 回答