Learn R Programming

fctutils (version 0.0.7)

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

Value

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

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.

Author

Kai Guo

Examples

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

Run the code above in your browser using DataLab