Home > Software design >  Order within and between elements of a list
Order within and between elements of a list

Time:07-01

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.

CodePudding user response:

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"

CodePudding user response:

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"

CodePudding user response:

You can use this function fn

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

fn(mylist)

  • output
[[1]]
[1] "I312" "O115" "Z432"

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

[[3]]
[1] "S123"

[[4]]
[1] "T123"

  • Related