【问题标题】:Remove common list elements in lists of lists in R删除 R 中列表列表中的常见列表元素
【发布时间】:2022-01-02 07:07:57
【问题描述】:

我有一个列表列表,我想删除这些子列表之间的共同元素。

例如

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)]

你能帮帮我吗?谢谢!

【问题讨论】:

  • 我修改了语法,谢谢

标签: r list


【解决方案1】:

根据更新,它是vectors 的list。将list 转换为带有enframe 的两列tibble/data.frame,将不同元素的计数变为filtersplit 回到listvectors

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))

【讨论】:

  • 谢谢,我会试试的
【解决方案2】:

基本 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))

【讨论】:

  • 谢谢你能解释一下为什么 mylist = mylist[!(mylist %in% common_elements)] 不起作用吗?
  • @Vesperal common_elements 是一个只有2 值的列表,mylist 是一个向量列表,而没有一个向量与2 完全相同,因此%in%申请mylist %in% common_elements时会返回false。
  • 明白谢谢!
  • 如果向量包含诸如“tata”“titi”“tata”之类的字符而不是数字,我将如何修改代码?
  • @Vesperal 然后你删除as.numeric
【解决方案3】:

列表列表的 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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 2016-05-28
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    相关资源
    最近更新 更多