从列表中删除重复的元素

Remove duplicated elements from list

我有 listcharacter vectors:

my.list <- list(e1 = c("a","b","c","k"),e2 = c("b","d","e"),e3 = c("t","d","g","a","f"))

我正在寻找一个 function,对于在 listvector 中出现不止一次的任何 character(在每个 vector一个character只能出现一次),只会保留第一次出现。

因此,此示例的结果列表为:

res.list <- list(e1 = c("a","b","c","k"),e2 = c("d","e"),e3 = c("t","g","f"))

请注意,list 中的整个 vector 可能会被删除,因此结果 list 中的元素数不一定必须等于输入 list.

我们可以unlist list,使用duplicated得到逻辑list,并根据逻辑索引[=]提取'my.list'中的元素15=]

un <- unlist(my.list)
res <- Map(`[`, my.list, relist(!duplicated(un), skeleton = my.list))
identical(res, res.list)
#[1] TRUE

这是使用 mapplysetdiffReduce 的替代方法。

# make a copy of my.list
res.list <- my.list
# take set difference between contents of list elements and accumulated elements
res.list[-1] <- mapply("setdiff", res.list[-1],
                                  head(Reduce(c, my.list, accumulate=TRUE), -1))

保留列表的第一个元素,我们计算后续元素和由 Reduce 使用 caccumulate=TRUE 参数生成的元素的累积向量列表。 head(..., -1) 删除包含所有元素的最终列表项,使长度对齐。

这个returns

res.list
$e1
[1] "a" "b" "c" "k"

$e2
[1] "d" "e"

$e3
[1] "t" "g" "f"

请注意,在 Reduce 中,我们可以将 c 替换为 function(x, y) unique(c(x, y)) 并实现相同的最终输出。

我发现这里的解决方案对我的理解来说非常复杂,因此寻求一种更简单的技术。假设您有以下列表。

my_list <- list(a = c(1,2,3,4,5,5), b = c(1,2,2,3,3,4,4), 
                
                d = c("Mary", "Mary", "John", "John"))

以下更简单的代码片段删除了重复项。

sapply(my_list, unique)

您将得到以下结果。

$a
[1] 1 2 3 4 5

$b
[1] 1 2 3 4

$d
[1] "Mary" "John"

简单中有美!