问题描述
我有与此类似的列表清单:
I have list of lists similar to this:
a <- list(
list(day = 5, text = "foo"),
list(text = "bar", day = 1),
list(text = "baz", day = 3),
list(day = 2, text = "quux")
)
字段数未知,并且字段混乱.
with unknown number of fields and the fields my be out of order.
如何根据日期对该列表进行排序?我需要将列表升序排列.我已经搜索过,但是我只找到了如何对向量进行排序.可以对列表进行排序吗?
how can I sort this list based on day? I need the list to be sorted ascending. I've search but I only found how to sort vectors. Is it possible to sort a list?
推荐答案
为了对给定的列表列表" a
进行排序,您可以尝试将sapply()
与提取运算符[[
一起使用,以从中检索数据列表.这些用于对order()
的调用:
In order to sort that given "list of lists" a
you can try to use sapply()
with the extraction operator [[
to retrieve data from the list. These are used in the call to order()
:
a[order(sapply(a, `[[`, i = "day"))]
#[[1]]
#[[1]]$day
#[1] 1
#
#[[1]]$text
#[1] "bar"
#
#
#[[2]]
#[[2]]$day
#[1] 2
#
#[[2]]$text
#[1] "quux"
# ...
如此评论中所建议,通过使用sapply()
中的匿名函数实现:
As suggested in this comment, this can also be achieved by using an anonymous function in sapply()
:
a[order(sapply(a, function(x) x$day))]
与OP一样,在函数定义中使用时也是如此:
This also works when used in a function definition as the OP did:
sortBy <- function(a, field) a[order(sapply(a, "[[", i = field))]
sortBy(a, "day")
请注意,我们需要将提取运算符[[
括在反引号或引号中.
Note that we need to enclose the extraction operator [[
either in backquotes or quotes.
这篇关于如何在R中排序列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!