![](/img/trans.png)
[英]Consolidate lists that share common elements in r with their corresponding list IDs?
[英]Remove common list elements in lists of lists in R
我有一个列表列表,我想删除这些子列表之间的公共元素。
例如
mylist = list(
c(1, 2, 3, 4),
c(2, 5, 6, 7),
c(4, 2, 8, 9)
)
变成
mylist = list(
c(1, 3),
c(5, 6, 7),
c(8, 9)
)
我首先创建了一个通用元素列表,并尝试从子列表中提取此列表,但它不起作用
common_elements = list(Reduce(intersect, mylist))
mylist = mylist[!(mylist %in% common_elements)]
你可以帮帮我吗? 谢谢 !
根据更新,它是一个vector
list
。 使用 enframe 将list
转换为两列 tibble/ enframe
,获取要filter
的不同元素的计数并split
回vector
list
library(dplyr)
library(tibble)
library(tidyr)
enframe(mylist) %>%
unnest(value) %>%
group_by(value) %>%
filter(n_distinct(name) == 1) %>%
with(., split(value, name)) %>%
unname
-输出
[[1]]
[1] 1 3
[[2]]
[1] 5 6 7
[[3]]
[1] 8 9
mylist <- list(c(1, 2, 3, 4), c(2, 5, 6, 7), c(4, 2, 8, 9))
一个基础 R 选项
> lut <- table(unlist(mylist))
> comm <- as.numeric(names(lut[lut > 1]))
> lapply(mylist, function(x) x[!x %in% comm])
[[1]]
[1] 1 3
[[2]]
[1] 5 6 7
[[3]]
[1] 8 9
mylist <- list(1:4, c(2, 5:7), c(4, 2, 8, 9))
列表列表的 tidyverse 选项。
library(tidyverse)
ls %>%
enframe() %>%
unnest(value) %>%
mutate(dupes = if_else(duplicated(value) == T, as.integer(value), NA_integer_)) %>%
filter(!value %in% dupes) %>%
group_by(name) %>%
mutate(X = list(value)) %>%
ungroup() %>%
distinct(X) %>%
deframe()
# [[1]]
# [[1]][[1]]
# [1] 1
#
# [[1]][[2]]
# [1] 3
#
#
# [[2]]
# [[2]][[1]]
# [1] 5
#
# [[2]][[2]]
# [1] 6
#
# [[2]][[3]]
# [1] 7
#
#
# [[3]]
# [[3]][[1]]
# [1] 8
#
# [[3]][[2]]
# [1] 9
数据
ls <- list(list(1, 2, 3, 4), list(2, 5, 6, 7), list(4, 2, 8, 9))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.