ft_replace_pattern {fctutils}R 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)

[Package fctutils version 0.0.7 Index]