Skip to content

The fctutils package provides a collection of utility functions for manipulating and analyzing factor vectors in R.

License

Notifications You must be signed in to change notification settings

guokai8/fctutils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

66 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fctutils: Advanced Factor Manipulation Utilities for R

CRAN version Project Status: Code Size:

The fctutils package provides a comprehensive suite of utilities for advanced manipulation and analysis of factor vectors in R. It offers tools for splitting, combining, reordering, filtering, and transforming factor levels based on various criteria. Designed to enhance the handling of categorical data, fctutils simplifies complex factor operations, making it easier to preprocess and analyze data in R.

Key Features:

  • Advanced Sorting and Reordering: Sort factor levels based on custom functions, external vectors, or associated data.
  • Factor Level Manipulation: Functions to split, collapse, map, insert and extract substrings from factor levels.
  • Grouping and Aggregation: Aggregate factor levels based on grouping variables or hierarchical categories.
  • Handling Missing Data: Impute missing values in factors using various methods.
  • Consistency Across Datasets: Ensure consistent factor levels across multiple vectors or datasets.

1. Software Usage

1.1 Installation

Install the package with its dependencies and load it for usage in R.

library(devtools) # Load the devtools package
install_github("guokai8/fctutils") # Install the package

2. Useful functions

2.1 Ordering and Sorting Factors

ft_pos Reorders the levels of a factor vector based on the characters at specified positions within the factor levels.

library(fctutils)
factor_vec <- factor(c('Apple', 'banana', 'Cherry', 'date', 'Fig', 'grape'))
# Reorder based on positions 1 and 3, case-insensitive
ft_pos(factor_vec, positions = c(1, 3))
# Reorder in decreasing order, case-sensitive
ft_pos(factor_vec, positions = 1:2, case = TRUE, decreasing = TRUE)

ft_count Reorders the levels of a factor vector based on the count of each level in the data.

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

# Reorder levels by decreasing count
ft_count(factor_vec)
# Reorder levels by increasing count
ft_count(factor_vec, decreasing = FALSE)

ft_sub Reorders the levels of a factor vector based on substrings extracted from the factor levels.

factor_vec <- factor(c('Apple', 'banana', 'Cherry', 'date', 'Fig', 'grape'))
# Reorder based on substring from position 2 to 4
ft_sub(factor_vec, start_pos = 2, end_pos = 4)

# Reorder from position 3 to end, case-sensitive
ft_sub(factor_vec, start_pos = 3, case = TRUE)

ft_freq Reorders the levels of a factor vector based on the total frequency of characters appearing in the vector.

factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'banana', 'apple', 'fig'))

# Reorder levels based on total character frequency
ft_freq(factor_vec)

# Reorder levels, case-sensitive
factor_vec_case <- factor(c('Apple', 'banana', 'Cherry', 'date', 'banana', 'apple', 'Fig'))
ft_freq(factor_vec_case, case = TRUE)

ft_char_freq Reorders the levels of a factor vector based on the frequency of characters at specified positions within the data.

factor_vec <- factor(c('apple', 'banana', 'apricot', 'cherry', 'banana', 'banana', 'date'))

# Reorder based on characters at positions 1 and 2
ft_char_freq(factor_vec, positions = 1:2)

# Reorder, case-sensitive, decreasing order
ft_char_freq(factor_vec, positions = c(1, 3), case = TRUE)

ft_substr_freq Reorders the levels of a factor vector based on the frequency of substrings extracted from the data.

factor_vec <- factor(c('苹果', '香蕉', '苹果', '樱桃', '香蕉', '香蕉', '日期'))

# Reorder based on substrings from position 1 to 1
ft_substr_freq(factor_vec, start_pos = 1, end_pos = 1)

# Reorder from position 2 to end
ft_substr_freq(factor_vec, start_pos = 2)
factor_vec <- factor(c('apple', 'banana', 'apricot', 'cherry', 'banana', 'banana', 'date'))
ft_substr_freq(factor_vec, start_pos = 2, end_pos=3)

ft_regex_freq Reorders the levels of a factor vector based on the frequency of substrings matching a regular expression.

factor_vec <- factor(c('apple', 'banana', 'apricot', 'cherry', 'blueberry', 'blackberry', 'date'))

# Reorder based on pattern matching 'a'
ft_regex_freq(factor_vec, pattern = 'a')

# Reorder with case-sensitive matching
ft_regex_freq(factor_vec, pattern = '^[A-Z]', case = TRUE)

ft_split Splits the levels of a factor vector using specified patterns or positions and reorders based on specified parts or criteria.

# Example factor vector with patterns
factor_vec <- factor(c('item1-sub1', 'item2_sub2', 'item3|sub3', 'item1-sub4'))

# Split by patterns '-', '_', or '|' and reorder based on the first part
ft_split(factor_vec, split_pattern = c('-', '_', '\\|'), part = 1)

# Use the second pattern '_' for splitting
ft_split(factor_vec, split_pattern = c('-', '_', '\\|'), use_pattern = 2, part = 2)

# Reorder based on character frequencies in the specified part
ft_split(factor_vec, split_pattern = '-', part = 2, char_freq = TRUE)

ft_len Reorders the levels of a factor vector based on the character length of each level.

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

# Sort levels by length
ft_len(factor_vec)

ft_sort 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 NAs.

factor_vec <- factor(c('apple', 'banana', 'cherry', 'date'))
by_vec <- c(2, 3, 1, NA)
ft_sort(factor_vec, by = by_vec)

# Example using a data frame column
data <- data.frame(
  Category = factor(c('apple', 'banana', 'cherry', 'date')),
  Value = c(2, 3, 1, NA)
)
ft_sort(data$Category, by = data$Value)

ft_sort_custom Reorders the levels of a factor vector based on a custom function applied to each level.

factor_vec <- factor(c('apple', 'banana', 'cherry'))

# Sort levels by reverse alphabetical order
ft_sort_custom(factor_vec, function(x) -rank(x))

# Sort levels by length of the level name
ft_sort_custom(factor_vec, function(x) nchar(x))

2.2 Replacing Factor Levels

ft_replace Replaces a specified level in a factor vector with a new level. If a position is provided, the new level is inserted at the specified position among the levels; otherwise, the original level order is preserved.

factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'fig', 'grape'))

# replace 'banana' as 'blueberry', and keep original order
ft_replace(factor_vec, old_level = 'banana', new_level = 'blueberry')

# replace 'banana' as 'blueberry'
ft_replace(factor_vec, old_level = 'banana', new_level = 'blueberry', position = 2)

ft_replace_pattern Replaces parts of the factor levels that match a specified pattern with a new string.

factor_vec <- factor(c('apple_pie', 'banana_bread', 'cherry_cake'))

# Replace '_pie', '_bread', '_cake' with '_dessert'
ft_replace_pattern(factor_vec, pattern = '_.*', replacement = '_dessert')

2.3 Filtering and Removing Factor Levels

ft_filter_freq Filters out factor levels that occur less than a specified frequency threshold and recalculates character frequencies excluding the removed levels. Offers options to handle NA values and returns additional information.

factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'banana', 'apple', 'fig', NA))

# Filter levels occurring less than 2 times and reorder by character frequency
ft_filter_freq(factor_vec, min_freq = 2)

# Filter levels, remove NA values, and return additional information
result <- ft_filter_freq(factor_vec, min_freq = 2, na.rm = TRUE, return_info = TRUE)
result$filtered_factor
result$removed_levels
result$char_freq_table

ft_filter_pos Removes factor levels where a specified character appears at specified positions within the levels.

factor_vec <- factor(c('apple', 'banana', 'apricot', 'cherry', 'date', 'fig', 'grape'))

# Remove levels where 'a' appears at position 1
ft_filter_pos(factor_vec, positions = 1, char = 'a')

# Remove levels where 'e' appears at positions 2 or 3
ft_filter_pos(factor_vec, positions = c(2, 3), char = 'e')

# Case-sensitive removal
factor_vec_case <- factor(c('Apple', 'banana', 'Apricot', 'Cherry', 'Date', 'Fig', 'grape'))
ft_filter_pos(factor_vec_case, positions = 1, char = 'A', case = TRUE)

ft_remove_levels Removes specified levels from a factor vector, keeping the remaining levels and their order unchanged.

factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'fig', 'grape'))

# Remove levels 'banana' and 'date'
ft_remove_levels(factor_vec, levels_to_remove = c('banana', 'date'))

ft_filter_func Removes levels from a factor vector based on a user-defined function.

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

# Remove levels that start with 'b'
ft_filter_func(factor_vec, function(x) !grepl('^b', x))

2.4 Merging Factor Vectors

ft_merge_similar Merges levels of a factor that are similar based on string distance.

factor_vec <- factor(c('apple', 'appel', 'banana', 'bananna', 'cherry'))

# Merge similar levels
ft_merge_similar(factor_vec, max_distance = 1)

ft_concat Combines multiple factor vectors into a single factor, unifying the levels.

factor_vec1 <- factor(c('apple', 'banana'))
factor_vec2 <- factor(c('cherry', 'date'))

# Concatenate factors
concatenated_factor <- ft_concat(factor_vec1, factor_vec2)
levels(concatenated_factor)

ft_combine Combines two vectors, which may be of unequal lengths, into a factor vector and sorts based on the levels of either the first or second vector.

vector1 <- c('apple', 'banana', 'cherry')
vector2 <- c('date', 'fig', 'grape', 'honeydew')

# Combine and sort based on vector1 levels
ft_combine(vector1, vector2, sort_by = 1)

# Combine and sort based on vector2 levels
ft_combine(vector1, vector2, sort_by = 2)

2.5 Other Useful Functions

ft_insert Inserts one or more new levels into a factor vector immediately after specified target levels. Targets can be identified by exact matches, positions, or pattern-based matching. Supports case sensitivity and handling of NA values. Can handle multiple insertions and maintains the original order of other levels. If a new level already exists in the factor and allow_duplicates is FALSE, it is moved to the desired position without duplication. If \code{allow_duplicates} is TRUE, unique duplicates are created.

factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'fig', 'grape'))
ft_insert(factor_vec, insert = 'date', target = 'banana', inplace = TRUE)
ft_insert(factor_vec, insert = c('date', 'grape'), positions = c(2, 4))
ft_insert(factor_vec, insert = 'honeydew', pattern = '^c')
factor_vec_na <- factor(c('apple', NA, 'banana', 'cherry', NA, 'date'))
ft_insert(factor_vec_na, insert = 'lychee', insert_after_na = TRUE)

ft_pairs Creates all unique pairwise combinations between factor_vec of a vector, with options for references, symmetry, NA handling, custom filtering, and output formats. Automatically handles factors by converting them to vectors and removes extra spaces from factor_vec before processing.

vec <- c(' A', 'b ', ' C ', 'D')
# Generate pairwise comparisons within vec
ft_pairs(vec)
# Use a custom preprocessing function to convert factor_vec to lower case
ft_pairs(vec, pre_fn = function(x) tolower(trimws(x)))
ft_pairs(vec, ref = c("A","C"))
elements <- c('apple', 'apricot', 'banana', 'blueberry', 'cherry', 'cranberry')
filter_fn <- function(df) {
  substr(df$Var1, 1, 1) == substr(df$Var2, 1, 1)
}
pairs <- ft_pairs(elements, filter_fn = filter_fn)

ft_intersect Combines multiple factor vectors and returns a factor vector containing only the levels common to all.

factor_vec1 <- factor(c('apple', 'banana', 'cherry'))
factor_vec2 <- factor(c('banana', 'date', 'cherry'))
factor_vec3 <- factor(c('banana', 'cherry', 'fig'))

# Get intersection of levels
ft_intersect(factor_vec1, factor_vec2, factor_vec3)

ft_union Combines multiple factor vectors and returns a factor vector containing all unique levels.

factor_vec1 <- factor(c('apple', 'banana'))
factor_vec2 <- factor(c('banana', 'cherry'))
factor_vec3 <- factor(c('date', 'fig'))

# Get union of levels
ft_union(factor_vec1, factor_vec2, factor_vec3)

ft_reorder_within Reorders the levels of a factor vector within groups defined by another factor vector.

data <- data.frame(
  item = factor(c('A', 'B', 'C', 'D', 'E', 'F')),
  group = factor(c('G1', 'G1', 'G1', 'G2', 'G2', 'G2')),
  value = c(10, 15, 5, 20, 25, 15)
)
data <- rbind(data, data)
# Reorder 'item' within 'group' by 'value'
data$item <- ft_reorder_within(data$item, data$group, data$value, mean)

ft_extract Extracts substrings from the levels of a factor vector based on a regular expression pattern and creates a new factor.

factor_vec <- factor(c('item123', 'item456', 'item789'))

# Extract numeric part
ft_extract(factor_vec, pattern = '\\d+')

# Extract with capturing group
factor_vec <- factor(c('apple: red', 'banana: yellow', 'cherry: red'))
ft_extract(factor_vec, pattern = '^(\\w+):', capture_group = 1)

ft_pad_levels Pads the levels of a factor vector with leading characters to achieve a specified width.

# Example factor vector
factor_vec <- factor(c('A', 'B', 'C', 'D'))

# Pad levels to width 4 using '0' as padding character
padded_factor <- ft_pad_levels(factor_vec, width = 4, pad_char = '0')
print(levels(padded_factor))
# Output: "000A" "000B" "000C" "000D"

# Pad levels to width 6 using '%A' as padding string
padded_factor <- ft_pad_levels(factor_vec, width = 6, pad_char = '%A')
print(levels(padded_factor))
# Output: "%%A%A" "%%A%B" "%%A%C" "%%A%D"

ft_level_stats Computes statistical summaries for each level of a factor vector based on associated numeric data. (group_by and summarize).

ft_pattern_replace Replaces substrings in factor levels that match a pattern with a replacement string.

ft_impute Replaces \code{NA} values in a factor vector using specified imputation methods.

ft_unique_comb Generates a new factor where each level represents a unique combination of levels from the input factors.

ft_map_func Transforms factor levels by applying a function that can include complex logic.

ft_collapse_lev Collapses specified levels of a factor into new levels based on a grouping list.

ft_duplicates Identifies duplicate levels in a factor vector and returns a logical vector indicating which elements are duplicates.

ft_dummy Generates a data frame of dummy variables (one-hot encoded) from a factor vector.

ft_replace_na Replaces \code{NA} values in a factor vector with a specified level.

ft_sample_levels Randomly selects a specified number of levels from a factor vector.

ft_apply Transforms factor levels by applying a function to each level.

ft_encode Converts the levels of a factor vector into numeric codes, optionally using a provided mapping.

3. Summary

The fctutils package provides a comprehensive set of functions to efficiently manage and manipulate factor vectors in R. From ordering and sorting to replacing, filtering, merging, and beyond, these tools enhance your ability to handle categorical data with ease. The additional essential functions further extend the package's capabilities, ensuring that all common factor operations are covered. I might change the logo in the future ^^

4. Contact information

For any questions please contact [email protected] or submit the issues to https://github.com/guokai8/fctutils/issues

About

The fctutils package provides a collection of utility functions for manipulating and analyzing factor vectors in R.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages