How to sort list in R?

匿名 (未验证) 提交于 2019-12-03 08:51:18

问题:

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?

回答1:

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" # ... 

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

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!