Search code examples
rlistreorderlist

Reorder elements in a list of lists


I've got a list of lists, and have the same number of objects, like this:

my_lists <- list(
  second = c('foo','bar','potato'),
  first = c(1,4,2),
  third = data_frame(first_name  = c(1,2,3),middle_name = c(34,5,3), 
   last_name = c(3,9,1))
   )
 my_lists

$second
[1] "foo"    "bar"    "potato"

$first
[1] 1 4 2

$third
# A tibble: 3 x 3
  first_name middle_name last_name
       <dbl>       <dbl>     <dbl>
1          1          34         3
2          2           5         9
3          3           3         1

I would like to reorder the items in each list to show something like this:

$name1
[1] "bar"    "foo"    "potato"

$name2
[1] 4 1 2

$name3
# A tibble: 3 x 3
  middle_name first_name last_name
        <dbl>      <dbl>     <dbl>
1          34          1         3
2           5          2         9
3           3          3         1

I've tried different assign new orders using indexing, but I've only managed to kill my lists.

Thanks.


Solution

  • We can do

    lapply(my_lists, function(x) if(is.vector(x)) sort(x) else 
             x  %>%
                 select(sort(names(.), decreasing = TRUE)))
    

    If it is a custom order

    lapply(my_lists, `[`, c(3, 2, 1))