2012-11-11 3 views
4

순열을 등가로 생각하면서 목록에 중복 요소가 포함되어 있는지 확인하고 싶습니다. 모든 벡터의 길이는 동일합니다.순열을 포함하여 목록에서 중복 찾기

이 작업을 수행하는 가장 효율적인 방법 (최단 실행 시간)은 무엇입니까? 지금은보다 효율적인 대안이 있다면 제가 궁금 중복

anyDuplicated(lapply(myList2, sort)) > 0 

을 점검하기 전에 목록의 각 구성원 정렬에 의존하고 들어

## 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. 

. 또한 ?duplicated 설명서에 "목록에이 기능을 사용하면 속도가 느릴 수 있습니다."라는 메시지가 표시됩니다. 목록에 더 적합한 다른 함수가 있습니까?

답변

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 
+0

벡터의 길이가 같다고 가정 할 수 있습니까? – Roland

+0

예, 여기에서는 벡터의 길이가 같다고 가정합니다. –

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 
+0

좋은 제안. 불행히도 작은 목록에는 효과적이지만 큰 목록에는 효율적이지 않습니다.
LargeList <- lapply (REP (100,30), 시료 80, F) smallList <- lapply (REP (4,4), 시료 3, F) 마이크로 벤치 (TEST1 (smallList) TEST2 (smallList), times = 300) 마이크로 벤치 마크 (test1 (LargeList), test2 (LargeList), times = 300) –

+0

미세 팁에 감사드립니다! –

-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 
+4

태그 r에주의하십시오. OP는 [R] (http://www.r-project.org/)를 사용하여 솔루션을 원합니다. – Roland