从列表中删除重复的元素 [英] Remove duplicated elements from list
问题描述
我的list
为character
vector
s:
my.list <- list(e1 = c("a","b","c","k"),e2 = c("b","d","e"),e3 = c("t","d","g","a","f"))
我正在寻找一个function
,对于在list
的vector
中多次出现的任何character
(在每个vector
中,character
只能出现一次) ,只会保留首次出现.
And I'm looking for a function
that for any character
that appears more than once across the list
's vector
s (in each vector
a character
can only appear once), will only keep the first appearance.
因此,此示例的结果列表为:
The result list for this example would therefore be:
res.list <- list(e1 = c("a","b","c","k"),e2 = c("d","e"),e3 = c("t","g","f"))
请注意,list
中的整个vector
可能会被消除,因此生成的list
中的元素数不一定必须等于输入list
.>
Note that it is possible that an entire vector
in the list
is eliminated so that the number of elements in the resulting list
doesn't necessarily have to be equal to the input list
.
推荐答案
我们可以unlist
list
,使用duplicated
获取逻辑list
,并根据逻辑索引
We can unlist
the list
, get a logical list
using duplicated
and extract the elements in 'my.list' based on the logical index
un <- unlist(my.list)
res <- Map(`[`, my.list, relist(!duplicated(un), skeleton = my.list))
identical(res, res.list)
#[1] TRUE
这篇关于从列表中删除重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!