Learn R Programming

fctutils (version 0.0.7)

ft_sort_custom: Sort Factor Levels Using a Custom Function

Description

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.

Usage

ft_sort_custom(factor_vec, sort_func, decreasing = FALSE, inplace = FALSE)

Value

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.

Arguments

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 FALSE.

inplace

Logical. If TRUE, returns a new factor vector with elements reordered to align with the new levels' order. If FALSE, returns a new factor vector with only the levels' order adjusted, leaving the data vector's elements' order unchanged. Defaults to FALSE.

Author

Kai Guo

Examples

Run this code
# 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

Run the code above in your browser using DataLab