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 33f8482 commit 8bd8ebe
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
12 changes: 10 additions & 2 deletions R/rescale_weights.R
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ rescale_weights <- function(data,

# check for existing variable names
if (any(c("pweights_a", "pweights_b", "pweights") %in% colnames(data))) {
insight::format_warning("The variable name for the rescaled weights already exists in the data. Existing columns will be overwritten.")
insight::format_warning("The variable name for the rescaled weights already exists in the data. Returned columns will be renamed into unique names.")
}

# check if weight has missings. we need to remove them first,
Expand Down Expand Up @@ -203,7 +203,15 @@ rescale_weights <- function(data,
})
}

do.call(cbind, list(data, out))
make_unique_names <- any(vapply(out, function(i) any(colnames(i) %in% colnames(data)), logical(1)))
# add weights to data frame
out <- do.call(cbind, list(data, out))
# check if we have to rename columns
if (make_unique_names) {
colnames(out) <- make.unique(colnames(out), sep = "_")
}

out
}


Expand Down
19 changes: 14 additions & 5 deletions tests/testthat/test-rescale_weights.R
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,20 @@ test_that("rescale_weights errors and warnings", {
)
nhanes_sample$pweights_a <- 1
expect_warning(
rescale_weights(
data = head(nhanes_sample, n = 30),
by = "SDMVSTRA",
probability_weights = "WTINT2YR"
),
{
out <- rescale_weights(
data = head(nhanes_sample, n = 30),
by = "SDMVSTRA",
probability_weights = "WTINT2YR"
)
},
regex = "The variable name"
)
expect_named(
out,
c(
"total", "age", "RIAGENDR", "RIDRETH1", "SDMVPSU", "SDMVSTRA",
"WTINT2YR", "pweights_a", "pweights_a_1", "pweights_b"
)
)
})

0 comments on commit 8bd8ebe

Please sign in to comment.