nouse
nouse

Reputation: 3471

Sorting a list by length of its elements

Sorry for basic question, but i have a list of elements, which are numeric vectors

str(list1)
    List of 34
     $ 1      : num [1:2037171] 98.3 98.2 98.1 97.4 97.9 98 97.7 98.1 98.4 98 ...
     $ 3      : num [1:692076] 98.8 98.1 97.6 96.6 96.4 96.9 96.1 95.8 96.7 96.5 ...
     $ 2      : num [1:82621] 97.7 97.7 97.4 97.7 98.4 98.1 97.4 98 97.6 98.3 ..
     .
     .
     .

, it seems that list.sort(or order) does not work, because list1 is not an atomic vector. I want to sort list1 by the length of its vectors. How is that possible? Sorry for "abusing" this site as my personal R tutorial. couldnt find the answer on google.

Upvotes: 4

Views: 1404

Answers (2)

user3603486
user3603486

Reputation:

len <- sapply(list1, length)
list1[order(len)]

Upvotes: 8

Roland
Roland

Reputation: 132969

You need to loop over the list to get the lengths:

mylist <- list(1:5, 1:10, 1:2)
mylist[order(sapply(mylist, length))]
# [[1]]
# [1] 1 2
# 
# [[2]]
# [1] 1 2 3 4 5
# 
# [[3]]
# [1]  1  2  3  4  5  6  7  8  9 10

Upvotes: 2

Related Questions