Sam
Sam

Reputation: 654

Sorting a list of lists based on the third element

I've got an object names x which is a list containing inner lists.

`x$population`

output
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 11

[[1]][[3]]
[1] 1


[[2]]
[[2]][[1]]
[1] 1

[[2]][[2]]
[1] 20

[[2]][[3]]
[1] 2

I want to be able to sort the list based on the third elements: x$population[[2]][[3]] but I have no idea how to do it.

I have no idea how to start so instead of got some mock code that re-creates the problem:

z <- list() 

z[[1]] <- list(1, 10, 0.5) 
z[[2]] <- list(1, 10, 0.87) 

How would I go about sorting z based on the third elements of each list (0.5, 0.87) such that the larger value is at the top.

Thanks in advance.

Upvotes: 0

Views: 235

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270020

1) Pick out the third elements, get their order and subscript the list by that:

z[order(sapply(z, "[[", 3))]

2) Another approach is to represent the data as a matrix a and then sort that:

a <- sapply(z, unlist)
a[, order(a[3, ])]

Upvotes: 4

Emmanuel-Lin
Emmanuel-Lin

Reputation: 1943

To do it explicitly: I would extract the third element and sort it.

I create a more complex list:

z <- list() 

z[[1]] <- list(1, 10, 0.5) 
z[[2]] <- list(1, 10, 0.87) 
z[[3]] <- list(1, 10, 0.2) 

I extract third element of each element:

thirdelt <- sapply(z, function(x)x[[3]])

Then I sort it:

thirdelt_order <- order(thirdelt)

Finaly I apply it:

z <- z[thirdelt_order]

Upvotes: 1

Related Questions