【问题标题】:Sort a named list in R在R中对命名列表进行排序
【发布时间】:2015-02-03 09:53:14
【问题描述】:

我有一个术语频率的命名列表,

> 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

我想根据频率将它们按降序排列。这个怎么做?我尝试了 sort, sort.list, order,但有错误提示他们不接受这种类型的列表。

【问题讨论】:

    标签: r list sorting hashmap


    【解决方案1】:

    如果列表很大并且涉及大型对象,那么只使用名称会更好吗?

     lst = lst[order(names(lst))]
    

    【讨论】:

    • 不同之处在于您的代码按列表元素名称排序,但 OP 想要按列表元素值排序。也就是说,你的代码就是我要找的。​​span>
    【解决方案2】:

    您可以通过unlist 尝试,然后使用order

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

    数据

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

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 2012-12-04
      • 2017-09-14
      • 1970-01-01
      • 2017-06-11
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      相关资源
      最近更新 更多