Skip to content

Commit

Permalink
Check if "weights" exists for vector-method
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Mar 7, 2024
1 parent 7a1f372 commit 15017c6
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Type: Package
Package: datawizard
Title: Easy Data Wrangling and Statistical Transformations
Version: 0.9.1.5
Version: 0.9.1.6
Authors@R: c(
person("Indrajeet", "Patil", , "[email protected]", role = "aut",
comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")),
Expand Down
2 changes: 1 addition & 1 deletion R/data_tabulate.R
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ data_tabulate.default <- function(x,
}

# validate "weights"
weights <- .validate_table_weights(weights, x)
weights <- .validate_table_weights(weights, x, weights_expression = insight::safe_deparse(substitute(weights)))

# we go into another function for crosstables here...
if (!is.null(by)) {
Expand Down
9 changes: 8 additions & 1 deletion R/data_xtabulate.R
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ print_html.dw_data_xtabulates <- function(x, big_mark = NULL, ...) {
}


.validate_table_weights <- function(weights, x) {
.validate_table_weights <- function(weights, x, weights_expression = NULL) {
if (!is.null(weights)) {
if (is.character(weights)) {
# If "weights" is a character string, must be of length 1
Expand Down Expand Up @@ -343,5 +343,12 @@ print_html.dw_data_xtabulates <- function(x, big_mark = NULL, ...) {
}
}

# exception: for vectors, if weighting variable not found, "weights" is NULL
# to check this, we check whether a weights expression was provided and weights
# is NULL, e.g. "weights = iris$not_found"
if (!is.null(weights_expression) && !identical(weights_expression, "NULL") && is.null(weights)) {
insight::format_error("The variable specified in `weights` was not found in `x`. Possibly misspelled?")
}

weights
}
1 change: 1 addition & 0 deletions tests/testthat/test-data_tabulate.R
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ test_that("data_tabulate, cross tables, errors weights", {
expect_error(data_tabulate(efc, "c172code", weights = efc$weights[-1]), regex = "Length of `weights`")
expect_error(data_tabulate(efc, "c172code", weights = "weigths"), regex = "not found")
expect_error(data_tabulate(efc, "c172code", weights = c("e16sex", "e42dep")), regex = "length 1")
expect_error(data_tabulate(efc$c172code, weights = efc$wweight), regex = "not found")
})


Expand Down

0 comments on commit 15017c6

Please sign in to comment.