简体   繁体   中英

How to sort list by first element

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

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 lapply to 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.

Similar to @MarkintheBox.

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

L[order(sapply(L,head,1),decreasing=T)]
# [[1]]
# [1] 3 3 3
# 
# [[2]]
# [1] 2 1 3
# 
# [[3]]
# [1] 1 3 1

Same as the others but using Map to extract the first element of each vector.

L <- list(c(2,1,3), c(3,3,3), c(1,3,1))
idx <- as.numeric(Map(function(vec){vec[1]},L))
L[order(idx, decreasing=TRUE)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM