From aad1da29dcfc3dac9f7b81dcb3af68d2a4cd7142 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Mon, 7 Oct 2024 13:51:10 +0200 Subject: [PATCH] add `label_lut()` --- R/label-lut.R | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 R/label-lut.R diff --git a/R/label-lut.R b/R/label-lut.R new file mode 100644 index 00000000..a42382c7 --- /dev/null +++ b/R/label-lut.R @@ -0,0 +1,22 @@ + +label_lut <- function(lut = character(), nomatch = NULL) { + + if (!is.character(lut)) { + cli::cli_abort("The {.arg lut} argument must be a character vector.") + } + if (!is_named2(lut)) { + cli::cli_abort("The {.arg lut} argument must have names.") + } + names <- names(lut) + values <- unname(lut) + + force(nomatch) + + function(x) { + i <- match(x, names, nomatch = NA_integer_) + out <- values[i] + missing <- is.na(i) + out[missing] <- if (is.null(nomatch)) x[missing] else nomatch + out + } +}