Learn R Programming

fctutils (version 0.0.7)

ft_replace_pattern: Replace Parts of Factor Levels Based on a Pattern

Description

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

Usage

ft_replace_pattern(factor_vec, pattern, replacement, replace_all = TRUE)

Value

A factor vector with levels modified.

Arguments

factor_vec

A factor vector to be modified.

pattern

A regular expression pattern to match.

replacement

A string to replace the matched parts.

replace_all

Logical. If TRUE (default), all occurrences of the pattern are replaced. If FALSE, only the first occurrence is replaced.

Author

Kai Guo

Examples

Run this code
# Example factor vector
factor_vec <- factor(c('apple_pie', 'banana_bread', 'cherry_cake'))

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

# Replace only the first occurrence of '_' with '-'
ft_replace_pattern(factor_vec, pattern = '_', replacement = '-', replace_all = FALSE)

Run the code above in your browser using DataLab