Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of list by key in R

Tags:

list

sorting

r

key

I have the following list:

myList <- list(list(a = 1,b = 1:5,x = 2),
               list(a = 7,b = 9.1,x = 3),
               list(a=-1, b = 0.2, x = 1))

And I would like to sort my elements in this list by criterion "x". I am at loss on how to do it. Any help would be greatly appreciated.

like image 657
S4M Avatar asked Dec 17 '12 11:12

S4M


1 Answers

myList[order(sapply(myList, "[[", "x"))]

will do the trick

[[1]]
[[1]]$a
[1] -1

[[1]]$b
[1] 0.2

[[1]]$x
[1] 1


[[2]]
[[2]]$a
[1] 1

[[2]]$b
[1] 1 2 3 4 5

[[2]]$x
[1] 2


[[3]]
[[3]]$a
[1] 7

[[3]]$b
[1] 9.1

[[3]]$x
[1] 3
like image 60
Sven Hohenstein Avatar answered Oct 02 '22 16:10

Sven Hohenstein