Order within and between elements of a list

Viewed 39

Suppose we have the following list of characters:

mylist <- list(c("I312","Z432","O115"),  
               c("S123"),  
               c("O978","T213"),  
               c("T123"))

mylist
[[1]]
[1] "I312" "Z432" "O115"
[[2]]
[1] "S123"
[[3]]
[1] "O978" "T213"
[[4]]
[1] "T123"

First I want to order within elements of mylist and then beetween elements of mylist due to the first component. The result should be as:

[[1]]
[1] "I312"  "O115"  "Z432"
[[2]] 
[1] "O978"  "T213"
[[3]] 
[1] "S123"
[[4]] 
[1] "T123"

Thanks for any help.

3 Answers

If you do not mind editing your list

> mylist=lapply(mylist,sort)
> mylist[order(unlist(lapply(mylist,"[[",1)))]

[[1]]
[1] "I312" "O115" "Z432"

[[2]]
[1] "O978" "T213"

[[3]]
[1] "S123"

[[4]]
[1] "T123"

Another way with just one apply,

new_l <- lapply(mylist, sort)

new_l[order(unlist(new_l)[c(1, head(cumsum(lengths(new_l)) + 1, -1))])]

[[1]]
[1] "I312" "O115" "Z432"

[[2]]
[1] "O978" "T213"

[[3]]
[1] "S123"

[[4]]
[1] "T123"

You can use this function fn

fn <- function(x){
    st <- lapply(x , sort)
    x[sapply(st , \(x) x[1]) |> order()]
}

fn(mylist)
  • output
[[1]]
[1] "I312" "O115" "Z432"

[[2]]
[1] "O978" "T213"

[[3]]
[1] "S123"

[[4]]
[1] "T123"

Related