排序列表的元素

时间:2016-06-22 23:17:40

标签: r

我有一个清单

str(overlaps)
List of 7
 $ a5: chr [1:6] "calc_a1c" "predmdx_flag" "bmi" "systolic" ...
 $ a2: chr [1:2] "age" "yr"
 $ a4: chr(0) 
 $ a6: chr(0) 
 $ a1: chr [1:2] "trig_3cat" "glipizide_flag"
 $ a3: chr [1:2] "email_flag" "statins_flag"
 $ a7: chr [1:4] "trig_3cat.>=200" "antihtn_flag" "black_flag" "gender.M"

我想重新排序列表,使得结果列表是元素按数字顺序排列的列表。即a1,a2,a3等

2 个答案:

答案 0 :(得分:5)

一些随机数据:

set.seed(42)
overlaps <- replicate(5, runif(3), simplify=FALSE)
names(overlaps) <- paste0("a", sample(5))
str(overlaps)
# List of 5
#  $ a5: num [1:3] 0.915 0.937 0.286
#  $ a4: num [1:3] 0.83 0.642 0.519
#  $ a1: num [1:3] 0.737 0.135 0.657
#  $ a3: num [1:3] 0.705 0.458 0.719
#  $ a2: num [1:3] 0.935 0.255 0.462

排序:

str(overlaps[ sort(names(overlaps)) ])
# List of 5
#  $ a1: num [1:3] 0.737 0.135 0.657
#  $ a2: num [1:3] 0.935 0.255 0.462
#  $ a3: num [1:3] 0.705 0.458 0.719
#  $ a4: num [1:3] 0.83 0.642 0.519
#  $ a5: num [1:3] 0.915 0.937 0.286

答案 1 :(得分:1)

这是r2evans&#39;的替代品。回答,这很好。我使用了他的示例数据集。

str(overlaps[order(names(overlaps))])

#List of 5
# $ a1: num [1:3] 0.737 0.135 0.657
# $ a2: num [1:3] 0.935 0.255 0.462
# $ a3: num [1:3] 0.705 0.458 0.719
# $ a4: num [1:3] 0.83 0.642 0.519
# $ a5: num [1:3] 0.915 0.937 0.286