mrsteve
mrsteve

Reputation: 4142

Sort a nested list by the length of the respective sublists

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"))

Upvotes: 3

Views: 1073

Answers (1)

James King
James King

Reputation: 6365

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

Upvotes: 5

Related Questions