Sorting By Functions in R Programming Language
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in R.
library(dplyr)
main <- function() {
fruits <- c("peach", "banana", "kiwi")
# We implement a comparison function for string lengths
len_cmp <- function(a, b) {
nchar(a) - nchar(b)
}
# Now we can use this custom comparison function to sort fruits by name length
sorted_fruits <- fruits[order(sapply(fruits, nchar))]
print(sorted_fruits)
# We can use the same technique to sort a list of values that aren't built-in types
Person <- function(name, age) {
list(name = name, age = age)
}
people <- list(
Person("Jax", 37),
Person("TJ", 25),
Person("Alex", 72)
)
# Sort people by age
sorted_people <- people[order(sapply(people, function(p) p$age))]
print(sorted_people)
}
main()
In this R code:
We use the
dplyr
library for some convenient functions.Instead of
slices.SortFunc
, we use R’sorder
function combined withsapply
to sort our collections.For the
Person
struct, we use a list in R as it’s the closest equivalent.The sorting of complex types (like our
Person
list) is done using a similar approach as with the strings, but we access theage
field of each person in the comparison function.
When you run this code, you should see output similar to:
[1] "kiwi" "peach" "banana"
[[1]]
[[1]]$name
[1] "TJ"
[[1]]$age
[1] 25
[[2]]
[[2]]$name
[1] "Jax"
[[2]]$age
[1] 37
[[3]]
[[3]]$name
[1] "Alex"
[[3]]$age
[1] 72
This demonstrates how to implement custom sorting in R, both for simple types like strings and for more complex custom types.