How to sort a list in R?

I have a list of similar lists:

a <- list(
  list(day = 5, text = "foo"),
  list(text = "bar", day = 1),
  list(text = "baz", day = 3),
  list(day = 2, text = "quux")
)

with an unknown number of fields and my fields are out of order.

How can I sort this list based on the day? I need a list to sort in ascending order. I'm looking, but I just found how to sort vectors. Can I sort the list?

+4
source share
1 answer

To sort this list, the List of Lists a, you can try using sapply()the extract operator [[to retrieve data from the list. They are used when calling 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"
# ...

, sapply():

a[order(sapply(a, function(x) x$day))]

, , OP:

sortBy <- function(a, field) a[order(sapply(a, "[[", i = field))]
sortBy(a, "day")

, [[ .

+4

Source: https://habr.com/ru/post/1675065/


All Articles