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.
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:
This demonstrates how to implement custom sorting in R, both for simple types like strings and for more complex custom types.