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?
There is a function in R that you can use (called the sort function) to sort your data in either ascending or descending order. The variable by which sort you can be a numeric, string or factor variable. You also have some options on how missing values will be handled: they can be listed first, last or removed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With