Skip to content

Commit

Permalink
fix, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Dec 18, 2024
1 parent dd8ca23 commit 33f8482
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
10 changes: 8 additions & 2 deletions R/rescale_weights.R
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
30 changes: 30 additions & 0 deletions tests/testthat/test-rescale_weights.R
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
})

0 comments on commit 33f8482

Please sign in to comment.