在R中对命名列表进行排序

Log*_*ang 10 sorting r list hashmap

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

> 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
Run Code Online (Sandbox Code Playgroud)

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

RTS*_*RTS 12

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

 lst = lst[order(names(lst))]
Run Code Online (Sandbox Code Playgroud)

  • 不同之处在于您的代码按列表元素名称排序,但 OP 希望按列表元素值排序。也就是说,你的代码就是我正在寻找的。 (3认同)

akr*_*run 9

您可以尝试unlist然后使用order

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

#$`3`
#[1] 7

#$`1`
#[1] 5

#$`2`
#[1] 4

#$`5`
#[1] 2
Run Code Online (Sandbox Code Playgroud)

数据

lst <- setNames(list(5,4,7,9,2),1:5)
Run Code Online (Sandbox Code Playgroud)