如何对R中的列表进行排序?

mjn*_*hol 12 sorting r list

我试图在R中对列表进行排序.每个子列表包含一个整数和一个字符串.我的目标是对列表进行排序,以便最终列表按整数按升序排序.下面是我想要完成的一个例子:

a <- list(-5,"help")
b <- list(3, "stack")
c <- list(1, "me")
d <- list(10, "overflow")

list.of.lists <- list(a,b,c,d)
magic.sort(list.of.lists)
# Below is not exactly how it would be displayed, but should be understandable
-5, "help"
1, "me"
3, "stack"
10, "overflow"
Run Code Online (Sandbox Code Playgroud)

在R中有一个很好的方法来实现这个结果吗?理想情况下,结果也应作为列表列表返回.

jor*_*ran 19

试试这个:

list.of.lists[order(sapply(list.of.lists,'[[',1))]
Run Code Online (Sandbox Code Playgroud)

  • @mjnichol - 从长远来看,你可以写:`sapply(list.of.lists,function(x)x [[1]])` - 它只是从每个列表中提取第一个元素然后将其作为向量返回然后传递给`order`.例如 - `a [[1]]`和`'[['(a,1)`是等价的. (2认同)