ft_len: Sort Factor Levels Based on Their Length

View source: R/fct_misc.R

ft_lenR Documentation

Sort Factor Levels Based on Their Length

Description

Reorders the levels of a factor vector based on the character length of each level. Optionally reorders the data vector's elements to align with the new levels' order.

Usage

ft_len(factor_vec, decreasing = FALSE, inplace = FALSE)

Arguments

factor_vec

A factor vector to be sorted.

decreasing

Logical. Should the ordering be decreasing by length? 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 levels reordered based on their length without changing the data vector's elements' order. Defaults to FALSE.

Value

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

Author(s)

Kai Guo

Examples

# Example factor vector
factor_vec <- factor(c('apple', 'banana', 'cherry', 'date'))

# Sort levels by length without reordering data elements
sorted_factor <- ft_len(factor_vec)
print(sorted_factor)
# [1] apple  banana cherry date
# Levels: apple date banana cherry

# Sort levels by length and reorder data elements
sorted_factor_inplace <- ft_len(factor_vec, inplace = TRUE)
print(sorted_factor_inplace)
# [1] date   apple  banana cherry
# Levels: apple date banana cherry

fctutils documentation built on Oct. 1, 2024, 1:07 a.m.