Reverses the coding of a vector. Supports numeric, logical, and factor inputs:
Numeric: Transforms values using
min + max - xLogical: Flips TRUE/FALSE
Factor: Reverses the order of levels
Arguments
- x
a vector (numeric, logical, or factor).
- min
optional numeric minimum. Must be provided together with
max. IfNULL(default), the observed minimum ofxis used.- max
optional numeric maximum. Must be provided together with
min. IfNULL(default), the observed maximum ofxis used.- na.rm
logical; whether to ignore
NAs when computing the range (numeric only). IfFALSEandNAs are present, a warning is issued andNAis returned for all values. Default isFALSE.
Errors
Throws an error if all values are NA, if only one of min/max
is provided, if min > max, or if x is not numeric, logical, or factor.
A warning is issued if values of x lie outside an explicitly
provided [min, max] range.
See also
Other data.recode:
asBinary(),
combLevels(),
dummy(),
mReplace(),
nf(),
recodeX(),
stringsAsFactors()
Examples
# Numeric
revCode(c(1, 2, 3, 4, 5))
#> [1] 5 4 3 2 1
# Numeric with explicit range (e.g., Likert scale)
revCode(c(1, 2, 3, 4, 5), min = 1, max = 5)
#> [1] 5 4 3 2 1
# Numeric with NAs
revCode(c(1, 2, NA, 4, 5), na.rm = TRUE)
#> [1] 5 4 NA 2 1
# Logical
revCode(c(TRUE, FALSE, TRUE))
#> [1] FALSE TRUE FALSE
# Factor
x <- factor(c("low", "medium", "high"), ordered = TRUE)
revCode(x)
#> [1] low high medium
#> Levels: medium < low < high
