diff --git a/R/rescale_weights.R b/R/rescale_weights.R index 340cdf2b4..dd8e0724a 100644 --- a/R/rescale_weights.R +++ b/R/rescale_weights.R @@ -171,8 +171,14 @@ rescale_weights <- function(data, insight::format_error("Argument `by` must be specified. Please provide one or more variable names in `by` that indicate the grouping structure (strata) of the survey data (level-2-cluster variable).") # nolint } - if (!by %in% colnames(data_tmp)) { - insight::format_error("The variable specified in `by` was not found in the data. Maybe misspelled?") # nolint + if (!all(by %in% colnames(data_tmp))) { + dont_exist <- by[which(!by %in% colnames(data_tmp))] + insight::format_error(paste0( + "The following variable(s) specified in `by` don't exist in the dataset: ", + text_concatenate(dont_exist), "." + ), + .misspelled_string(colnames(data_tmp), dont_exist, "Possibly misspelled?") + ) } if (nest && length(by) < 2) { diff --git a/tests/testthat/test-rescale_weights.R b/tests/testthat/test-rescale_weights.R index 504157180..bf94387e5 100644 --- a/tests/testthat/test-rescale_weights.R +++ b/tests/testthat/test-rescale_weights.R @@ -40,3 +40,33 @@ test_that("rescale_weights nested works as expected", { ) ) }) + + +test_that("rescale_weights errors and warnings", { + data(nhanes_sample) + expect_error( + rescale_weights( + data = head(nhanes_sample, n = 30), + by = c("a", "SDMVSTRA", "c"), + probability_weights = "WTINT2YR" + ), + regex = "The following" + ) + expect_error( + rescale_weights( + data = head(nhanes_sample, n = 30), + by = NULL, + probability_weights = "WTINT2YR" + ), + regex = "must be specified" + ) + nhanes_sample$pweights_a <- 1 + expect_warning( + rescale_weights( + data = head(nhanes_sample, n = 30), + by = "SDMVSTRA", + probability_weights = "WTINT2YR" + ), + regex = "The variable name" + ) +})