1#' Anonymise factor levels
2#'
3#' Replaces factor levels with arbitrary numeric identifiers. Neither
4#' the values nor the order of the levels are preserved.
5#'
6#' @param f A factor.
7#' @param prefix A character prefix to insert in front of the random labels.
8#' @export
9#' @examples
10#' gss_cat$relig %>% fct_count()
11#' gss_cat$relig %>% fct_anon() %>% fct_count()
12#' gss_cat$relig %>% fct_anon("X") %>% fct_count()
13fct_anon <- function(f, prefix = "") {
14  levels <- paste0(prefix, zero_pad(seq_len(nlevels(f))))
15
16  f <- lvls_revalue(f, sample(levels))
17  lvls_reorder(f, match(levels, levels(f)))
18}
19
20digits <- function(x) nchar(max(x, na.rm = TRUE))
21
22zero_pad <- function(x) {
23  sprintf(paste0("%0", digits(x), "d"), x)
24}
25