ft_replace_pattern: Replace Parts of Factor Levels Based on a Pattern

View source: R/single_replace.R

ft_replace_patternR Documentation

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)

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.

Value

A factor vector with levels modified.

Author(s)

Kai Guo

Examples

# 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)

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