按相应子列表的长度对嵌套列表进行排序 [英] Sort a nested list by the length of the respective sublists

查看:184
本文介绍了按相应子列表的长度对嵌套列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按子列表的长度对嵌套列表进行排序:

How can I sort a nested list by the length of the sublists:

l <- list(list("a","b","c"), list("d","e"), list("f"))

使用它应该返回:

list(list("f"), list("d","e"), list("a","b","c"))

推荐答案

我会用过

l[order(sapply(l, length))]

@Arun的评论中给出的解决方案

The solution given in the comment of @Arun

l[order(vapply(l, length, 1L))]

通过告诉R长度函数返回的所有内容都是整数,可以提供一些性能优势:对于vapply,您基本上给R给出了函数将返回哪种类型的示例,这可以节省返回的强制时间值以适合单个原子向量."参见:

may give some performance advantage by telling R that everything returned by the length function will be an integer: "For vapply, you basically give R an example of what sort of thing your function will return, which can save some time coercing returned values to fit in a single atomic vector." See:

R分组功能:sapply vs. lapply vs. apply. vs. tapply vs. by vs.聚合

这篇关于按相应子列表的长度对嵌套列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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