0
votes

How do I sort a list alphabetically by name using purrr (or some other package in the tidyverse)?

Basically I'm looking for the equivalent of:

lst <- list(b = letters, c = 1:100, a = runif(10))
lst <- lst[order(names(lst))]

Thanks!

3
What's wrong with your current solution? Why do you want to replace it?sindri_baldur
I'm looking for a tidyverse solution and I'm curious to know if it exists or this is indeed the only way to do it.enricoferrero

3 Answers

1
votes

Here's little verbose solution:

library(tidyverse)
library(magrittr)

lst %>%
  tibble(
    lst = .,
    nm = names(.)
  ) %>%
  arrange(nm) %$%
  set_names(lst, nm)
1
votes

Terribly verbose but forces you to use ate least one tidyverse function:

tmp <- names(lst)
purrr::map(tmp, ~ {f <- sort(tmp, partial = 1)[1]; tmp <<- setdiff(tmp, f); lst[[f]]})
1
votes

You could use base function with magrittr:

library(magrittr)

lst %>%
  .[order(names(.))]