在列表中查找重复项,包括排列组合

4
我希望确定一个列表是否包含任何重复元素,同时将排列视为等效。所有向量的长度都相等。
最有效的方法(运行时间最短)是什么?
## SAMPLE DATA
a  <- c(1, 2, 3)
b  <- c(4, 5, 6)
a.same <- c(3, 1, 2)

## BOTH OF THSE LISTS SHOULD BE FLAGGED AS HAVING DUPLICATES
myList1 <- list(a, b, a)
myList2 <- list(a, b, a.same)


# CHECK FOR DUPLICATES
anyDuplicated(myList1) > 0  # TRUE
anyDuplicated(myList2) > 0  # FALSE, but would like true. 

现在我正在采用对列表中的每个成员进行排序,然后检查重复项的方法。

anyDuplicated( lapply(myList2, sort) ) > 0

我在想是否有更有效的替代方案。此外,在 ?duplicated 文档中指出:“对列表使用这个方法可能会很慢”。是否有其他更适合列表的函数?
3个回答

1

您可以使用 setequal

myList1 <- list(a, b, a)
myList2 <- list(a, b, a.same)
myList3 <- list(a,b)

test1 <- function(mylist) anyDuplicated( lapply(mylist, sort) ) > 0

test1(myList1)
#[1] TRUE
test1(myList2)
#[1] TRUE
test1(myList3)
#[1] FALSE

test2 <- function(mylist) any(combn(length(mylist),2,
                           FUN=function(x) setequal(mylist[[x[1]]],mylist[[x[2]]])))

test2(myList1)
#[1] TRUE
test2(myList2)
#[1] TRUE
test2(myList3)
#[1] FALSE

library(microbenchmark)

microbenchmark(test1(myList2),test2(myList2))
#Unit: microseconds
#            expr     min       lq   median       uq     max
#1 test1(myList2) 142.256 150.9235 154.6060 162.8120 247.351
#2 test2(myList2)  63.306  70.5355  73.8955  79.5685 103.113

好的建议。不幸的是,它对于较小的列表效果很好,但对于较大的列表效率不高。LargeList <- lapply(rep(100,30), sample, 80, F) smallList <- lapply(rep(4,4), sample, 3, F)microbenchmark(test1(smallList), test2(smallList), times=300) microbenchmark(test1(LargeList), test2(LargeList), times=300) - Ricardo Saporta

0

这个怎么样?

a  <- c(1, 2, 3)
b  <- c(4, 5, 6)
a.same <- c(3, 1, 2)
myList1 <- list(a, b, a)
myList2 <- list(a, b, a.same)

# For exact duplicated values: List1
DF1 <- do.call(rbind, myList1)  # From list to data.frame
ind1 <- apply(DF1, 2, duplicated) # logical matrix for duplicated values
DF1[ind1] # finding duplicated values  
[1] 1 2 3

# For permutations: List2
DF2 <- do.call(rbind, myList2)
ind2 <- apply(apply(DF2, 1, sort), 1, duplicated)
DF2[ind2] # duplicated values
[1] 3 1 2

我们可以假设这些向量长度相等吗? - Roland
是的,在这里假设向量具有相同的长度。 - Jilber Urbina

-3
    a=[1,2,3]
    b=[4,5,6]
    samea=[3,2,1]

 list1=list(a+b+a) and list(a+b+sames) both of this will create a list with same element
   [1, 2, 3, 4, 5, 6, 3, 2, 1]

   ####so finding duplicate Function

   def findDup(x):
         for i in x:
               if x.count(i)>1: return True

         return False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接