ft_sort | R Documentation |
Sorts the levels of a factor vector based on the values of another vector or a column from a data frame. Handles cases where the sorting vector may contain ‘NA's. Optionally reorders the data vector’s elements to align with the new levels' order.
ft_sort(factor_vec, by, decreasing = FALSE, na_last = TRUE, inplace = FALSE)
factor_vec |
A factor vector whose levels are to be sorted. |
by |
A vector or data frame column used as the basis for sorting. Must be the same length as 'factor_vec'. |
decreasing |
Logical. Should the sorting be in decreasing order? Default is |
na_last |
Logical. Should 'NA' values be put last? Default is |
inplace |
Logical. If |
A factor vector with levels sorted based on 'by'. Depending on the inplace
parameter, the data vector's elements may also be reordered.
# Example using a vector without reordering data elements
factor_vec <- factor(c('apple', 'banana', 'cherry', 'date'))
by_vec <- c(2, 3, 1, NA)
sorted_factor <- ft_sort(factor_vec, by = by_vec)
print(sorted_factor)
# [1] apple banana cherry date
# Levels: cherry apple banana date
# Example using a vector and reordering data elements
sorted_factor_inplace <- ft_sort(factor_vec, by = by_vec, inplace = TRUE)
print(sorted_factor_inplace)
# [1] cherry apple banana date
# Levels: cherry apple banana date
# Example using a data frame column without reordering data elements
data <- data.frame(
Category = factor(c('apple', 'banana', 'cherry', 'date')),
Value = c(2, 3, 1, NA)
)
sorted_factor_df <- ft_sort(data$Category, by = data$Value)
print(sorted_factor_df)
# [1] apple banana cherry date
# Levels: cherry apple banana date
# Example using a data frame column and reordering data elements
sorted_factor_df_inplace <- ft_sort(data$Category, by = data$Value, inplace = TRUE)
print(sorted_factor_df_inplace)
# [1] cherry apple banana date
# Levels: cherry apple banana date
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.