Learn R Programming

fctutils (version 0.0.7)

ft_len: 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)

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.

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.

Author

Kai Guo

Examples

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

Run the code above in your browser using DataLab