gpt4 book ai didi

r - 在列表中查找重复项,包括排列

转载 作者:行者123 更新时间:2023-12-04 10:07:52 24 4
gpt4 key购买 nike

我想确定列表是否包含任何重复元素,同时将排列视为等效。所有向量的长度相等。

实现这一目标的最有效方法(最短运行时间)是什么?

## 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文档,它表明“将它用于列表可能会很慢”。还有其他更适合列表的函数吗?

最佳答案

您可以使用 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

关于r - 在列表中查找重复项,包括排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com