Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list by length of its elements

Tags:

r

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.

like image 645
nouse Avatar asked Oct 23 '25 14:10

nouse


2 Answers

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

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
like image 43
Roland Avatar answered Oct 26 '25 04:10

Roland