Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list in R?

Tags:

list

sorting

r

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?

like image 628
jcubic Avatar asked Apr 18 '17 16:04

jcubic


People also ask

Is there a sort function in R?

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.


1 Answers

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.

like image 87
Uwe Avatar answered Oct 10 '22 01:10

Uwe