如何按第一个元素对列表进行排序 [英] How to sort list by first element

查看:303
本文介绍了如何按第一个元素对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似矢量的列表:

I have a list of vectors looking like:

[[1]]
[1] 2 1.0 3.0

[[2]]
[1] 3 3 3

[[3]]
[1] 1 3.0 1.0

并且我希望它按每个矢量的第一个元素以降序排序,如下所示:

and I want it to be sorted by first element of every vector, in decreasing order, like that:

[[1]]
[1] 3 3 3

[[2]]
[1] 2 1.0 3.0    

[[3]]
[1] 1 3.0 1.0

我正在寻找一种看起来像(当然不起作用)的解决方案:

I am looking for a solution that would look like (of course it is not working):

list.sortby(function (x) x[1])

推荐答案

我假设您的示例不应该导致将列表的第二个元素放在结果的第一个元素中?如果这是正确的,则可以使用lapply进行所需的操作:

I assumed that your example should not have resulted in putting the second element of your list in the first element of the result? If this is right, you can use lapplyto do what you want:

L <- list(c(2,1,3), c(3,3,3), c(1,3,1))
L
lapply(L, sort)

如果按列表中每个向量的第一个值排序,则可以通过以下方式完成:

If you are ordering by the first value in each vector of you list, then this can be done in the following way:

L[order(sapply(L, function(x) x[1], simplify=TRUE), decreasing=TRUE)]

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

[[2]]
[1] 2 1 3

[[3]]
[1] 1 3 1

在您的示例中,看起来您想要递减的顺序.

From your example, it looks like you want the decreasing order.

这篇关于如何按第一个元素对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆