diff --git a/R/recode_into.R b/R/recode_into.R index 308124e56..22ca801e3 100644 --- a/R/recode_into.R +++ b/R/recode_into.R @@ -136,6 +136,7 @@ recode_into <- function(..., all_recodes <- NULL all_same_length <- NULL + new_values <- NULL # check recode values for (i in seq_len(n_params)) { # get type of all recode values @@ -158,16 +159,37 @@ recode_into <- function(..., # save type and length of recode values all_recodes <- c(all_recodes, type) all_same_length <- c(all_same_length, len_matches) + new_values <- c(new_values, value_type) } # if we have mixed types, warn user if (!is.null(all_recodes) && !all(all_recodes == all_recodes[1])) { - insight::format_error("Recoding not carried out. Not all recode values are of the same type.") + wrong_type <- which(all_recodes != all_recodes[1]) + insight::format_error( + paste( + "Recoding not carried out. Not all recode values are of the same type.", + sprintf( + "For instance, the new value of the first pattern, `%s`, is of type `%s`. The new value of the %s recode pattern, `%s`, is of type `%s`.", # nolint + insight::color_text(new_values[1], "cyan"), + insight::color_text(all_recodes[1], "cyan"), + .number_to_text(wrong_type[1]), + insight::color_text(new_values[wrong_type[1]], "cyan"), + insight::color_text(all_recodes[wrong_type[1]], "cyan") + ) + ) + ) } # all inputs of correct length? if (!is.null(all_same_length) && !all(all_same_length == all_same_length[1])) { + wrong_length <- which(all_same_length != all_same_length[1]) insight::format_error( "The matching conditions return vectors of different length.", - "Please check if all variables in your recode patterns are of the same length." + paste( + "Please check if all variables in your recode patterns are of the same length.", + sprintf( + "For instance, the first and the %s recode pattern return vectors of different length.", + .number_to_text(wrong_length[1]) + ) + ) ) } @@ -232,7 +254,7 @@ recode_into <- function(..., # don't show msg again overwrite_NA_msg <- FALSE insight::format_alert( - "Missing values in original variable are overwritten by default value. If you want to preserve missing values, set `preserve_na = TRUE`." + "Missing values in original variable are overwritten by default value. If you want to preserve missing values, set `preserve_na = TRUE`." # nolint ) } } @@ -240,3 +262,28 @@ recode_into <- function(..., out } + +.number_to_text <- function(x) { + if (is.null(x) || is.na(x)) { + return("") + } + if (x == 1) { + "first" + } else if (x == 2) { + "second" + } else if (x == 3) { + "third" + } else if (x == 4) { + "fourth" + } else if (x == 5) { + "fifth" + } else if (x == 21) { + "twenty-first" + } else if (x == 22) { + "twenty-second" + } else if (x == 23) { + "twenty-third" + } else { + paste0(x, "th") + } +}