Function that matches cases in a vector and replaces them with user-specified values. Robust to NA values.

replace_cases(x, to_replace, replace_with, default = NA)

Arguments

x

A vector.

to_replace

Either a vector of values to replace, or a list of vectors for the sets of values to replace.

replace_with

A vector of values, either a single value or a vector matching in length with to_replace.

Value

A vector.

Examples

# Example vector
x <- rep( LETTERS[1:4], each = 3 )
# Replace all cases
replace_cases( x, c( 'A', 'B', 'C', 'D' ), 1:4 )
#>  [1] 1 1 1 2 2 2 3 3 3 4 4 4
# Replace some cases and use default value for others
replace_cases( x, c( 'A', 'B', 'C' ), 1:3 )
#>  [1]  1  1  1  2  2  2  3  3  3 NA NA NA
# Replace combinations of cases
replace_cases( x, list( c( 'A', 'B' ), c( 'C', 'D' ) ), 1:2 )
#>  [1] 1 1 1 1 1 1 2 2 2 2 2 2

# Robust to NA values
x <- c( 1, 1, 2, 2, NA, NA )
replace_cases( x, c( 1, 2, NA ), c( 'A', 'B', '' ) )
#> [1] "A" "A" "B" "B" ""  ""