Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of lists in R?

Tags:

list

sorting

r

I am attempting to sort a list of lists in R. Each sublist contains an integer and a character string. My goal is to order the lists such that the final list is sorted by the integers in ascending order. Below is an example of what I am trying to accomplish:

a <- list(-5,"help")
b <- list(3, "stack")
c <- list(1, "me")
d <- list(10, "overflow")

list.of.lists <- list(a,b,c,d)
magic.sort(list.of.lists)
# Below is not exactly how it would be displayed, but should be understandable
-5, "help"
1, "me"
3, "stack"
10, "overflow"

Is there a nice way within R to achieve this result? Ideally the result should be returned as a list of lists as well.

like image 545
mjnichol Avatar asked Jan 22 '15 23:01

mjnichol


People also ask

Can we sort a list in R?

R provides a different way to sort the data either in ascending or descending order; Data-analysts, and Data scientists use order() , sort() and packages like dplyr to sort data depending upon the structure of the obtained data.

How do I list in ascending order in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

How do you sort a list in Elixir?

To sort a list of strings alphabetically, you can just use Enum. sort/1 , which will order items by their default order (which is alphabetic ordering for strings). To sort a list by a different property, such as string length, you can use Enum. sort_by/2 , which takes a mapper function as second argument.

Can you sort a list of lists Java?

Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.


2 Answers

Try this:

list.of.lists[order(sapply(list.of.lists,'[[',1))]
like image 190
joran Avatar answered Sep 30 '22 15:09

joran


You have a lot of structure in your list.of.lists. Depending on other processing you need to do, you might want to make it into a two-dimensional list like so:

list.2d <- sapply(list.of.lists, cbind)

and, possibly, from there, into a data frame like this:

df <- data.frame(t(list.2d))

(Technically, a data frame is a type of list.) Sorting by a particular set of columns, and extracting subsets of elements can then be a bit more conventional. (Though I also really like the accepted answer here.)

like image 42
Rick Avatar answered Sep 30 '22 15:09

Rick