Learn R Programming

fctutils (version 0.0.7)

ft_sort: Sort Factor Levels Based on Another Vector or Column

Description

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.

Usage

ft_sort(factor_vec, by, decreasing = FALSE, na_last = TRUE, inplace = FALSE)

Value

A factor vector with levels sorted based on `by`. Depending on the inplace parameter, the data vector's elements may also be reordered.

Arguments

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

na_last

Logical. Should `NA` values be put last? Default is TRUE.

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.

Examples

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

Run the code above in your browser using DataLab