Sort Strings in Numeric or Alphabetic Order

str_sort() returns the sorted elements in numerical and alphabetical order.

library(stringr)x <- c("cheese", "grape", "apple", NA)str_sort(x)

Output:

[1] "apple" "cheese" "grape" NA

You can sort by the reverse order: from z to a, and from big to small numbers.

str_sort(x, decreasing = T)

Output:

[1] "grape" "cheese" "apple" NA

All NA values are positioned at the end of the output vector by default. Alternatively, you can return the NA values at the beginning of the output.

str_sort(x, na_last = F)

Output:

[1] NA "apple" "cheese" "grape"

String elements started with numbers are sorted first, beginning with the first digit and progressing to the second digit, and so forth. These elements are returned at the beginning of the sorted vector.

x <- c("abc", "100", "101", "x30", "2", "50")str_sort(x)

Output:

[1] "100" "101" "2" "50" "abc" "x30"

Use numeric = TRUE to sort numbers in strings.

str_sort(x, numeric = T)

Output:

[1] "2" "50" "100" "101" "abc" "x30"

str_order() returns a vector of integers that indicate the position of the sorted elements in the original input vector.

str_order(x) 

Output:

[1] 2 3 5 6 1 4

As such, str_sort(x) is equivalent to x[str_order(x)].