Sort a named list in R

12,046

Solution 1

You can try by unlist and then use order

lst[order(unlist(lst),decreasing=TRUE)]
#  $`4`
#[1] 9

#$`3`
#[1] 7

#$`1`
#[1] 5

#$`2`
#[1] 4

#$`5`
#[1] 2

data

lst <- setNames(list(5,4,7,9,2),1:5)

Solution 2

If the list is large and involves large objects, would it be better to just use names?

 lst = lst[order(names(lst))]
Share:
12,046
Logan Yang
Author by

Logan Yang

I'm interested in machine learning and full-stack development. Program in Python, Java, JavaScript/Node.js, Go, R.

Updated on June 19, 2022

Comments

  • Logan Yang
    Logan Yang about 2 years

    I have a named list of term frequencies,

    > list
    $`in the`
    [1] 67504
    
    $`to the`
    [1] 36666
    
    $`of the`
    [1] 79665
    
    $`on the`
    [1] 31261
    
    $`to be`
    [1] 25862
    
    $`for the`
    [1] 28332
    

    I want to sort them into descending order according to the frequencies. How to do this? I tried sort, sort.list, order but had errors saying they don't accept this type of list.

  • Josh
    Josh over 3 years
    The difference is your code orders by list element names, but the OP wants to order by list element values. That said, your code is what I was looking for.