I have a list of lists, I would like to remove the common elements between these sublists.
For example
mylist = list(
c(1, 2, 3, 4),
c(2, 5, 6, 7),
c(4, 2, 8, 9)
)
becomes
mylist = list(
c(1, 3),
c(5, 6, 7),
c(8, 9)
)
I first created a list of the common elements and tried to substrate this list from the sublist but it does not work
common_elements = list(Reduce(intersect, mylist))
mylist = mylist[!(mylist %in% common_elements)]
Could you help me ? Thank you !
CodePudding user response:
Based on the update, it is a list
of vector
s. Convert the list
to a two column tibble/data.frame with enframe
, get the count of distinct elements to filter
and split
back to a list
of vector
s
library(dplyr)
library(tibble)
library(tidyr)
enframe(mylist) %>%
unnest(value) %>%
group_by(value) %>%
filter(n_distinct(name) == 1) %>%
with(., split(value, name)) %>%
unname
-output
[[1]]
[1] 1 3
[[2]]
[1] 5 6 7
[[3]]
[1] 8 9
data
mylist <- list(c(1, 2, 3, 4), c(2, 5, 6, 7), c(4, 2, 8, 9))
CodePudding user response:
A base R option
> 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
data
mylist <- list(1:4, c(2, 5:7), c(4, 2, 8, 9))
CodePudding user response:
A tidyverse option for a list of lists.
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
Data
ls <- list(list(1, 2, 3, 4), list(2, 5, 6, 7), list(4, 2, 8, 9))