Description Usage Arguments Value Examples
This is a vectorised version of switch()
: you can replace
numeric values based on their position, and character values by their
name. This is an S3 generic: dplyr provides methods for numeric, character,
and factors. For logical vectors, use if_else
1 2 3 |
.x |
A vector to modify |
... |
Replacments. These should be named for character and factor
All replacements must be the same type, and must have either length one or the same length as x. |
.default |
If supplied, all values not otherwise matched will
be given this value. If not supplied and if the replacements are
the same type as the original values in |
.missing |
If supplied, any missing values in |
.ordered |
If |
A vector the same length as .x
, and the same type as
the first of ...
, .default
, or .missing
.
recode_factor()
returns a factor whose levels are in the
same order as in ...
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | # Recode values with named arguments
x <- sample(c("a", "b", "c"), 10, replace = TRUE)
recode(x, a = "Apple")
recode(x, a = "Apple", .default = NA_character_)
# Named arguments also work with numeric values
x <- c(1:5, NA)
recode(x, `2` = 20L, `4` = 40L)
# Note that if the replacements are not compatible with .x,
# unmatched values are replaced by NA and a warning is issued.
recode(x, `2` = "b", `4` = "d")
# If you don't name the arguments, recode() matches by position
recode(x, "a", "b", "c")
recode(x, "a", "b", "c", .default = "other")
recode(x, "a", "b", "c", .default = "other", .missing = "missing")
# Supply default with levels() for factors
x <- factor(c("a", "b", "c"))
recode(x, a = "Apple", .default = levels(x))
# Use recode_factor() to create factors with levels ordered as they
# appear in the recode call. The levels in .default and .missing
# come last.
x <- c(1:4, NA)
recode_factor(x, `1` = "z", `2` = "y", `3` = "x")
recode_factor(x, `1` = "z", `2` = "y", .default = "D")
recode_factor(x, `1` = "z", `2` = "y", .default = "D", .missing = "M")
# When the input vector is a compatible vector (character vector or
# factor), it is reused as default.
recode_factor(letters[1:3], b = "z", c = "y")
recode_factor(factor(letters[1:3]), b = "z", c = "y")
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.