ft_replace: Replace a Factor Level and Optionally Insert at Specified...

View source: R/single_replace.R

ft_replaceR Documentation

Replace a Factor Level and Optionally Insert at Specified Position

Description

Replaces a specified level in a factor vector with a new level. If a position is provided, the new level is inserted at the specified position among the levels; otherwise, the original level order is preserved.

Usage

ft_replace(factor_vec, old_level, new_level, position = NULL)

Arguments

factor_vec

A factor vector in which a level will be replaced.

old_level

A character string specifying the level to be replaced.

new_level

A character string specifying the new level to replace the old level.

position

Optional. A positive integer specifying the position to insert the new level in the levels vector. If NULL, the original level order is preserved. Default is NULL.

Value

A factor vector with the level replaced and the new level optionally inserted at the specified position.

Author(s)

Kai Guo

Examples

#
factor_vec <- factor(c('apple', 'banana', 'cherry', 'date', 'fig', 'grape'))

# replace 'banana' as 'blueberry', and keep original order
ft_replace(factor_vec, old_level = 'banana', new_level = 'blueberry')

# replace 'banana' as 'blueberry'
ft_replace(factor_vec, old_level = 'banana', new_level = 'blueberry', position = 2)

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