有必要创建一个随机字母列表。然后按字母顺序排序。要创建这样的列表,我使用以下代码:
# Creating a random vector of letters
random_text_data = sample(letters, 10)
random_text_data
# Convert to list
list_text_data = as.list(random_text_data)
list_text_data
在控制台中我得到以下信息:
> random_text_data
[1] "h" "m" "q" "b" "z" "i" "y" "f" "d" "e"
> # Convert to list
> list_text_data = as.list(random_text_data)
> list_text_data
[[1]]
[1] "h"
[[2]]
[1] "m"
[[3]]
[1] "q"
[[4]]
[1] "b"
[[5]]
[1] "z"
[[6]]
[1] "i"
[[7]]
[1] "y"
[[8]]
[1] "f"
[[9]]
[1] "d"
[[10]]
[1] "e"
现在我需要按字母顺序排序。我尝试过以下方法:
# Sort list alphabetically
sort_data = sort(list_text_data)
但是出现错误:
> sort_data = sort(list_text_data)
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) :
'x' must be elementary
应该如何排序?
这里有一个方法,不需要
unlist()
。用随机字母制作列表后,用列表的内容为列表分配名称。然后对列表中的名称进行排序。
random_text_data = sample(letters, 10)
[1] "c" "v" "m" "g" "h" "l" "d" "i" "u" "y"
list_text_data = as.list(random_text_data)
list_text_data <- setNames(list_text_data, list_text_data)
list_text_data[order(names(list_text_data))]
$c
[1] "c"
$d
[1] "d"
$g
[1] "g"
$h
[1] "h"
$i
[1] "i"
$l
[1] "l"
$m
[1] "m"
$u
[1] "u"
$v
[1] "v"
$y
[1] "y"
受@zx8754的回答启发,你实际上不需要更改列表的名称,你可以在
setNames
中使用order
,那么输出将是一个未命名的列表。
list_text_data[order(names(setNames(list_text_data, list_text_data)))]
[[1]]
[1] "c"
[[2]]
[1] "d"
[[3]]
[1] "g"
[[4]]
[1] "h"
[[5]]
[1] "i"
[[6]]
[1] "l"
[[7]]
[1] "m"
[[8]]
[1] "u"
[[9]]
[1] "v"
[[10]]
[1] "y"
将字符转换为整数,然后排序:
# reproducible example data
set.seed(1); random_text_data = sample(letters, 3)
list_text_data = as.list(random_text_data)
# [[1]]
# [1] "y"
#
# [[2]]
# [1] "d"
#
# [[3]]
# [1] "g"
# sort
list_text_data[ order(sapply(list_text_data, utf8ToInt)) ]
# [[1]]
# [1] "d"
#
# [[2]]
# [1] "g"
#
# [[3]]
# [1] "y"
在对元素进行排序之前,我们可能必须先展平列表。我们可以尝试像下面这样的
sort
+ unlist
relist(sort(unlist(list_text_data)), list_text_data)
将列表操作从第一步移至最后一步。 更少的工作,更好的产出。
list(sort(random_text_data))