
Relabel a categorical variable by name, never by position
Source:R/categorical_guard.R
morie_safe_relabel.RdA relabel is only safe when every old level is mapped BY NAME to its new
label. Assigning a vector of labels by position (the levels<- idiom,
or factor(x, labels = ...) with labels in a different order from the
codes) is the mechanism behind the documented four-way rotation in the
OHRC 2023 correction, so this function refuses unnamed mappings outright.
Usage
morie_safe_relabel(x, mapping, keep = character())Value
A factor with the new labels, levels in the order of mapping,
carrying a morie_recode_audit attribute (see
morie_safe_recode).
Examples
f <- factor(c("W", "B", "O", "W"))
morie_safe_relabel(f, c(W = "White", B = "Black", O = "Other"))
#> [1] White Black Other White
#> attr(,"morie_recode_audit")
#> attr(,"morie_recode_audit")$mapping
#> W B O
#> White Black Other
#>
#> attr(,"morie_recode_audit")$kept
#> character(0)
#>
#> attr(,"morie_recode_audit")$checksum
#> [1] 992b6c4a35a3cea9e5875c90f562a3259fe9f08f1eb2fac9754d7c5b5f52bdd3
#>
#> Levels: White Black Other
try(morie_safe_relabel(f, c("Black", "Other", "White")))
#> Error : morie_safe_relabel: `mapping` must be NAMED (old label = new label). Assigning labels by POSITION is how four race codes were rotated in a published analysis (OHRC correction, 26 January 2023): the labels were in alphabetical order, the codes were not.