在R

时间:2018-05-13 07:17:37

标签: arrays r string list sorting

我有这个列表 afinn_score_retweeted 。它在控制台中显示时的值如下:

$`0`
[1] 4486797
$`2`
[1] 19538
$`-2`
[1] 30731
$`7`
[1] 1300
$`1`
[1] 3952
$`5`
[1] 37232
$`3`
[1] 153
$`-4`
[1] 156
$`-1`
[1] 5165
$`-7`
[1] 0
$`-3`
[1] 1982
$`12`
[1] 1467
$`6`
[1] 37
$`4`
[1] 291

我想将字符串索引从小值排序到大值,输出应如下所示:

$`-7`
[1] 0
$`-4`
[1] 156
$`-3`
[1] 1982
$`-2`
[1] 30731
$`-1`
[1] 5165
$`0`
[1] 4486797
$`1`
[1] 3952
$`2`
[1] 19538
$`3`
[1] 153
$`4`
[1] 291
$`5`
[1] 37232
$`6`
[1] 37
$`7`
[1] 1300
$`12`
[1] 1467

我将如何在R中这样做?任何帮助将非常感谢。我试着没有运气排序功能。

1 个答案:

答案 0 :(得分:1)

一定很简单。您应该使用[运算符。如果您的列表是ll

ll[as.character(sort(as.numeric(names(ll))))]

# $`-7`
# [1] 200
# 
# $`-1`
# [1] 200
# 
# $`0`
# [1] 100
# 
# $`10`
# [1] 20
# 
# $`50`
# [1] 200
# 
# $`100`
# [1] 30

数据:

ll <- list("0" = 100, "-7" = 200, "100" = 30, "-1" = 200, "10" = 20, "50" = 200)

ll
# $`0`
# [1] 100
# 
# $`-7`
# [1] 200
# 
# $`100`
# [1] 30
# 
# $`-1`
# [1] 200
# 
# $`10`
# [1] 20
# 
# $`50`
# [1] 200