merge_factor | R Documentation |
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.
merge_factor(.data, arg_list, contr_f = NULL, ...)
.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., |
... |
Optional arguments to pass in to |
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.
A factor with levels and values as you specified.
merge_levels
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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.