combine_levels | R Documentation |
Convenience functions to combine multiple levels of a vector into a new or
existing level(s). combine_levels
and combine_regex
are
similar in use, but the latter is more useful for unstructured text which
can be grouped by regular expressions.
combine_levels(
x,
levels,
labels = NULL,
ordered = is.ordered(x),
regex = FALSE,
...
)
combine_regex(
x,
levels,
labels = NULL,
ordered = is.ordered(x),
keep.original = TRUE,
...
)
x |
a vector |
levels |
for for for values of |
labels |
for for |
ordered |
logical; if |
regex |
logical; if |
... |
additional arguments passed to |
keep.original |
deprecated, will be ignored |
combine_levels
will always return a factor. The levels will be
in the order of x
plus any new levels (i.e., labels
).
combine_regex
returns an integer vector if character labels
are not given; otherwise, a character vector is returned.
factor2
; recoder
## combine numeric, character, or factor
x <- rep(1:3, each = 2)
combine_levels(x, 1:2, 1)
combine_levels(x, list(1:2, 3), c('a', 'b'))
## use a named list to get the same as above
combine_levels(x, list(a = 1:2, b = 3))
## use NULL list to combine others
combine_levels(x, list(b = 3, others = NULL))
## levels may be swapped without losing original distinction
combine_levels(x, list('3' = 1:2, '1' = 3))
combine_levels(x, list('1' = 3, '3' = 1:2))
## combine by regular expression
x <- letters[1:5]
combine_regex(x, 'a')
combine_regex(x, c('a', 'b'))
combine_regex(x, c('a', 'b|c|e'))
## character labels return a labeled factor
combine_regex(x, 'a', c('a', 'b')) ## a -> a; else -> b
combine_regex(x, '[a-c]', c('ABC', 'Others')) ## a,b,c -> ABC; else Others
## levels passed as a list
combine_regex(x, list(ABC = c('a', 'b', 'c'))) ## d,e are unchanged
combine_regex(x, list(ABC = '[a-c]', Others = NULL)) ## d,e are changed
## combine_levels(..., regex = TRUE) returns the same as above
combine_levels(x, '[a-c]', c('ABC', 'Others'), regex = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.