ft_sort_custom | R Documentation |
Reorders the levels of a factor vector based on a custom function applied to each level. Optionally reorders the data vector's elements to align with the new levels' order.
ft_sort_custom(factor_vec, sort_func, decreasing = FALSE, inplace = FALSE)
factor_vec |
A factor vector to sort. |
sort_func |
A function that takes a character vector (the levels) and returns a vector of the same length to sort by. |
decreasing |
Logical. Should the sort be decreasing? Default is |
inplace |
Logical. If |
A factor vector with levels reordered according to the custom function. Depending on the inplace
parameter, the data vector's elements may also be reordered.
Kai Guo
# Example factor vector
factor_vec <- factor(c('apple', 'banana', 'cherry'))
# Sort levels by reverse alphabetical order without reordering data elements
sorted_custom <- ft_sort_custom(factor_vec, function(x) -rank(x))
print(sorted_custom)
# [1] apple banana cherry
# Levels: cherry banana apple
# Sort levels by reverse alphabetical order and reorder data elements
sorted_custom_inplace <- ft_sort_custom(factor_vec, function(x) -rank(x), inplace = TRUE)
print(sorted_custom_inplace)
# [1] cherry banana apple
# Levels: cherry banana apple
# Sort levels by length of the level name without reordering data elements
sorted_custom_length <- ft_sort_custom(factor_vec, function(x) nchar(x))
print(sorted_custom_length)
# [1] apple banana cherry
# Levels: apple cherry banana
# Sort levels by length of the level name and reorder data elements
sorted_custom_length_inplace <- ft_sort_custom(factor_vec, function(x) nchar(x), inplace = TRUE)
print(sorted_custom_length_inplace)
# [1] apple cherry banana
# Levels: apple cherry banana
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.