Learn R Programming

fctutils (version 0.0.7)

ft_extract: 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)

Value

A new factor vector containing the extracted substrings.

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.

Author

Kai Guo

Examples

Run this code
# 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)

Run the code above in your browser using DataLab