Learn R Programming

fctutils (version 0.0.7)

ft_freq: Reorder Factor Levels Based on Character Frequency

Description

Reorders the levels of a factor vector based on the frequency of characters in each level's name. Supports case sensitivity, descending order, and optionally reorders the data vector's elements to align with the new levels' order.

Usage

ft_freq(factor_vec, case = FALSE, decreasing = TRUE, inplace = FALSE)

Value

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

Arguments

factor_vec

A factor vector whose levels will be reordered.

case

Logical. If TRUE, case is considered during frequency calculation. If FALSE, all characters are converted to lowercase before frequency calculation. Defaults to FALSE.

decreasing

Logical. If TRUE, the levels are ordered in decreasing order based on character frequency. Defaults to 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.

Author

Kai Guo

Examples

Run this code
# Example 1: Reorder levels based on character frequency without reordering data elements
factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'fig', 'grape'))
new <- ft_freq(
  factor_vec,
  case = FALSE,
  decreasing = TRUE,
  inplace = FALSE
)
print(new)
# [1] apple  banana cherry date   fig    grape
# Levels: apple banana date cherry fig grape

# Example 2: Reorder levels based on character frequency and reorder data elements
new_inplace <- ft_freq(
  factor_vec,
  case = FALSE,
  decreasing = TRUE,
  inplace = TRUE
)
print(new_inplace)
# [1] apple  banana date   cherry fig    grape
# Levels: apple banana date cherry fig grape

# Example 3: Reorder levels in decreasing order based on character frequency
# without reordering data elements
new_dec <- ft_freq(
  factor_vec,
  case = FALSE,
  decreasing = TRUE,
  inplace = FALSE
)
print(new_dec)
# [1] apple  banana cherry date   fig    grape
# Levels: apple banana date cherry fig grape

# Example 4: Reorder levels with case sensitivity and reorder data elements
factor_vec_case <- factor(c('Apple', 'banana', 'Cherry', 'date', 'Fig', 'grape'))
new_case <- ft_freq(
  factor_vec_case,
  case = TRUE,
  decreasing = TRUE,
  inplace = TRUE
)
print(new_case)
# [1] Apple   banana  Cherry date    Fig     grape
# Levels: cherry Apple banana grape Fig date

# Example 5: Reorder levels based on character frequency, allowing insertion beyond string length
factor_vec_short <- factor(c('go', 'dog', 'cat', 'bird'))
new_short <- ft_freq(
  factor_vec_short,
  case = FALSE,
  decreasing = TRUE,
  inplace = FALSE
)
print(new_short)
# [1] go   dog  cat  bird
# Levels: cat dog bird go

Run the code above in your browser using DataLab