Low-level encoding and factor building
Arguments
- x
A vector of values
- from, to
Vectors of the same length. Values in
xare matched tofromand replaced with the corresponding value into.- strict
If
TRUE, values inxthat are not matched tofromwill be replaced withNA. IfFALSE, they will be left unchanged.- exclude
Values in
xthat will not be matched when recoding;excludewill take priority overfrominencode().- levels
A vector of unique values. If
NULL, the unique values inxare used.
Value
encode() A vector of the same length as x with values
replaced according to from and to.
fact() A factor vector with levels corresponding to the
unique values in x (or levels if provided).
Details
encode() is a general purpose function for replacing values in a
vector.
fact() is a low-level function for building factor vectors. It does
not perform any sort()ing of levels (unlink base::factor()). Re-leveling
can be done by applying encode() to the levels of a factor object.
Examples
fact(strsplit("factor function", "")[[1L]], exclude = " ")
#> [1] f a c t o r <NA> f u n c t i o n
#> Levels: f a c t o r u n i
# encode() can be used to for the same utility as factor(x, levels, labels)
# (note: applying to levels can be more efficient)
(x <- fact(strsplit("jordan", "")[[1L]]))
#> [1] j o r d a n
#> Levels: j o r d a n
levels(x) <- encode(levels(x), from = c("a", "o"), to = "*")
x
#> [1] j * r d * n
#> Levels: j * r d n
