'How to sort a list alphabetically?
It is necessary to create a list of random letters of the alphabet. And then sort it alphabetically. To create such a list, I use the following code:
# 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
In the console I get the following:
> 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"
Now I need to sort it alphabetically. I have tried the following:
# Sort list alphabetically
sort_data = sort(list_text_data)
But get error:
> sort_data = sort(list_text_data)
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) :
'x' must be elementary
How should you sort?
Solution 1:[1]
Convert character to integer, then order:
# 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"
Solution 2:[2]
We may have to flatten the list first before sorting the elements. We can try the sort + unlist like below
relist(sort(unlist(list_text_data)), list_text_data)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zx8754 |
| Solution 2 | ThomasIsCoding |
