I have list of lists similar to this:
a <- list( list(day = 5, text = "foo"), list(text = "bar", day = 1), list(text = "baz", day = 3), list(day = 2, text = "quux") )
with unknown number of fields and the fields my be out of order.
how can I sort this list based on day? I need the list to be sorted ascending. I've search but I only found how to sort vectors. Is it possible to sort a list?
In order to sort that given "list of lists" a
you can try to use sapply()
with the extraction operator [[
to retrieve data from the list. These are used in the call to order()
:
a[order(sapply(a, `[[`, i = "day"))] #[[1]] #[[1]]$day #[1] 1 # #[[1]]$text #[1] "bar" # # #[[2]] #[[2]]$day #[1] 2 # #[[2]]$text #[1] "quux" # ...
As suggested in this comment, this can also be achieved by using an anonymous function in sapply()
:
a[order(sapply(a, function(x) x$day))]
This also works when used in a function definition as the OP did:
sortBy <- function(a, field) a[order(sapply(a, "[[", i = field))] sortBy(a, "day")
Note that we need to enclose the extraction operator [[
either in backquotes or quotes.