merge_factor: Combine/rename/reorder levels in a factor

View source: R/merge_levels.R

merge_factorR Documentation

Combine/rename/reorder levels in a factor

Description

Instead of using ifelse statements to combine values in a factor (e.g. when you want to simplify variables for a model), you can rename, combine, and reorder the levels of a factor with one easy list. If there's an empty level that isn't included, merge_factor will warn you, but go ahead and remove it.

Usage

merge_factor(.data, arg_list, contr_f = NULL, ...)

Arguments

.data

The factor you want to respecify.

arg_list

A list whose names are the new levels, whose values are the old levels, and whose order is the new order of the levels.

contr_f

Optional function to determine contrast code. I.e., contr.sum, or contr.helmert, etc. If unused, merge_factor won't touch the contrast coding. Automatically names contrasts as would appear by default.

...

Optional arguments to pass in to contr_f.

Details

The same effect could be achieved with something like:
levels(my_factor) <- c(old1=new1, old2=new1, old3=new2, old4=new2),
but merge_factor() saves typing by letting you type the inverse–in essence:
levels(my_factor) <- list(new1=c(old1, old2), new2=c(old3, old4)).
This was before I knew about revalue or purrr's mapvalues (which no longer exists). It's still marginally more useful than either of these in my opinion, however.

Value

A factor with levels and values as you specified.

See Also

merge_levels

Examples

my_factor <- factor(c("d", "b", "c", "d", "a", "a", "d", "d"))
levels(my_factor)
merge_factor(my_factor, list("CIsFirst"="c", "AandB"=c("a","b"), "d"))

# Demonstrates how contrasts are named by default
merged_factor <- merge_factor(my_factor,
                              list("CIsFirst"="c", "AandB"=c("a", "b"), "d"),
                              contr.helmert)
merged_factor
contrasts(merged_factor)


burchill/zplyr documentation built on Feb. 2, 2023, 11:01 a.m.