knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library(rank)
Rank provides a customizable alternative to the built-in rank()
function. The package offers the following features:
Frequency-based ranking of categorical variables: choose whether to rank based on alphabetic order or element frequency.
Control over sorting order: Use desc=TRUE
to rank based on descending or ascending order.
fruits <- c("Apple", "Orange", "Apple", "Pear", "Orange") # rank alphabetically smartrank(fruits) # rank based on frequency smartrank(fruits, sort_by = "frequency") # rank based on descending order of frequency smartrank(fruits, sort_by = "frequency", desc = TRUE)
# rank numerically smartrank(c(1, 3, 2)) # rank numerically based on descending order smartrank(c(1, 3, 2), desc = TRUE)
We can use order
to sort vectors based on their ranks. For example, we can sort the fruits
vector based on the frequency of each element.
fruits <- c("Apple", "Orange", "Apple", "Pear", "Orange") ranks <- smartrank(fruits, sort_by = "frequency") fruits[order(ranks)]
smartrank
can be used to arrange data.frames based on one or more columns, while maintaining complete control over how each column contributes to the final row order.
For example, we can sort the following dataframe based on frequency of fruits, but break any ties based on the alphabetical order of the picker.
data = data.frame( fruits = c("Apple", "Orange", "Apple", "Pear", "Orange"), picker = c("Elizabeth", "Damian", "Bob", "Cameron", "Alice") ) # Rank fruits so the most frequently picked fruits will come first fruit_ranks <- smartrank(data$fruits, sort_by = "frequency", desc=TRUE) # Rank pickers in alphabetical order picker_ranks <- smartrank(data$picker, sort_by = "alphabetical", desc=FALSE) # Sort dataframe by the fruit_ranks, then the picker_ranks (hierarchical) data[order(fruit_ranks, picker_ranks),]
An equivalent way to hierarchically sort data.frames is to use smartrank()
in the tidyverse arrange()
function.
library(dplyr) arrange( data, smartrank(fruits, "frequency", desc = TRUE), smartrank(picker, "alphabetical", desc = FALSE) )
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.