ft_extract: Extract Substrings from Factor Levels

View source: R/fct_misc.R

ft_extractR Documentation

Extract Substrings from Factor Levels

Description

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

Usage

ft_extract(factor_vec, pattern, capture_group = 0)

Arguments

factor_vec

A factor vector from which substrings will be extracted.

pattern

A regular expression pattern to match.

capture_group

An integer specifying which capture group to extract if using capturing groups in the pattern. Default is 0, which extracts the entire match.

Value

A new factor vector containing the extracted substrings.

Author(s)

Kai Guo

Examples

# Example factor vector
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)

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