S4M
S4M

Reputation: 4671

Sorting a list of list by key in R

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.

Upvotes: 6

Views: 999

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

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

Upvotes: 8

Related Questions