3

How can I sort a nested list by the length of the sublists:

l <- list(list("a","b","c"), list("d","e"), list("f"))

using this it should give back:

list(list("f"), list("d","e"), list("a","b","c"))
Ben Bolker
  • 192,494
  • 24
  • 350
  • 426
mrsteve
  • 4,062
  • 23
  • 59
  • 4
    `l[order(vapply(l, length, 1L))]` ? (feel free to add it as an answer, if this is what you're looking for). – Arun May 17 '14 at 22:18

1 Answers1

5

I would have used

l[order(sapply(l, length))]

The solution given in the comment of @Arun

l[order(vapply(l, length, 1L))]

may give some performance advantage by telling R that everything returned by the length function will be an integer: "For vapply, you basically give R an example of what sort of thing your function will return, which can save some time coercing returned values to fit in a single atomic vector." See:

R Grouping functions: sapply vs. lapply vs. apply. vs. tapply vs. by vs. aggregate

Community
  • 1
  • 1
James King
  • 5,849
  • 3
  • 24
  • 40