R中列表的排序列表:排序一列表'值取决于其他列表'的值

时间:2021-02-18 14:05:40

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"

1 个解决方案

#1


5  

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)]

#1


5  

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)]