Home > Software design >  How to split a list based on distinct element
How to split a list based on distinct element

Time:01-26

I would like to split a list according to each distinct element

mylist <- list("first","first","second")

### What I would like
# A first list
list("first","first")
# A second list
list("second")

CodePudding user response:

If you do the one-liner:

list2env(split(mylist, unlist(mylist)), globalenv())

Then you have the two lists in your global environment:

dput(first)
#> list("first", "first")

dput(second)
#> list("second")

Created on 2023-01-25 with reprex v2.0.2

CodePudding user response:

You can split your dataframe according to unique values:

newlist <- split(mylist, match(mylist, unique(unlist(mylist))))
newlist

# $`1`
# $`1`[[1]]
# [1] "first"
# 
# $`1`[[2]]
# [1] "first"
# 
# 
# $`2`
# $`2`[[1]]
# [1] "second"

Then, use list2env to add the list to your environment:

list2env(newlist, envir = .GlobalEnv)

CodePudding user response:

You can use lapply() to make a nested list of lists of each unique element:

mylist2 <- lapply(unique(mylist), \(x) mylist[mylist == x])

mylist2
[[1]]
[[1]][[1]]
[1] "first"

[[1]][[2]]
[1] "first"


[[2]]
[[2]][[1]]
[1] "second"
  • Related