从列表中删除重复的元素 [英] Remove duplicated elements from list

查看:105
本文介绍了从列表中删除重复的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的listcharacter vector s:

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只能出现一次) ,只会保留首次出现.

And I'm looking for a function that for any character that appears more than once across the list's vectors (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆