Collapse multiple original values of a vector into single new values. An
alternative to nested ifelse()
statements, recode
,
and revalue
.
recode(x, ..., .default = NULL, .na = NA, factor = FALSE) binary_recode(x, one, .na = NA)
x | a vector |
---|---|
... | a sequence of arguments where the name is the replacement and the value are the elements to be replaced. |
.default | a vector of length 1. The value is assigned to all elements
of |
.na | a vector. All values in |
factor | If TRUE, returned the recoded version of |
one | for |
a vector of the same length as x
in which all substitutions
specified in ...
(or one
in binary_recode()
) are made.
binary_recode()
always returns a numeric vector while recode()
returns a vector coerced according to the various recoding arguments provided.
Further information on recode()
's primary value mapping arguments:
...
Any number of named arguments in which for each
argument, any values occurring in x
will be recoded to the name of
the argument. There are no defaults in recode()
, so recode(x)
with no additional arguments should be equivalent to identity(x)
.na
Any values of x
matching values in the vector
provided to .na
will be recoded to NA
.
.default
Any values of x
not matched by either
...
(or one
) or .na
will be recoded to the value
passed to .default
.
binary_recode()
wraps recode()
but accepts only a single
recoding argument (one
) instead of ...
), sets
.default
to 0
, and always returns an integer vector.
s <- c("a", "b", "c", "d", "e", "f", NA) recode(s, `1` = c("a", "b"), .default = 0)#> [1] "1" "1" "0" "0" "0" "0" NArecode(s, `1` = c("a", "b"), .na = c(NA, "d", "e"))#>#> [1] "1" "1" "c" NA NA "f" NArecode(s, `1` = c("a", "b"))#>#> [1] "1" "1" "c" "d" "e" "f" NArecode(s, `1` = c("a", "b"), factor = TRUE)#>#> [1] 1 1 c d e f <NA> #> Levels: 1 c d e fbinary_recode(s, one = c("a", "b"))#> [1] 1 1 0 0 0 0 NA