Marta Karas
Marta Karas

Reputation: 5165

Sort list of lists in R: sort one lists' value depending on other lists' value

I need some help with sorting a list of lists. Suppose I have a list of children given as following:

a <- list(name = "Ann", age = 9)
b <- list(name = "Bobby", age = 17)
c <- list(name = "Alex", age = 6)

my.list <- list(a, b, c)

I would like to sort their names by their age, so receive the following:

> "Alex" "Ann" "Bobby"

Upvotes: 5

Views: 4234

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226732

a <- list(name = "Ann", age = 9)
b <- list(name = "Bobby", age = 17)
c <- list(name = "Alex", age = 6)

L <- list(a,b,c)
ages <- sapply(L,"[[","age")
names <- sapply(L,"[[","name")
names[order(ages)]

Upvotes: 5

Related Questions