Skip to content

Commit

Permalink
Fix factor arg handling (#999)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrjohns authored Jun 15, 2024
1 parent 373fc08 commit a45d4f7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
21 changes: 11 additions & 10 deletions R/data.R
Original file line number Diff line number Diff line change
Expand Up @@ -186,18 +186,19 @@ process_data <- function(data, model_variables = NULL) {
# generating a decimal point in write_stan_json
if (data_variables[[var_name]]$type == "int"
&& !is.integer(data[[var_name]])) {
if (!isTRUE(all(is_wholenumber(data[[var_name]])))) {
# Don't warn for NULL/NA, as different warnings are used for those
if (!isTRUE(any(is.na(data[[var_name]])))) {
warning("A non-integer value was supplied for '", var_name, "'!",
" It will be truncated to an integer.", call. = FALSE)
if (!is.factor(data[[var_name]])) {
if (!isTRUE(all(is_wholenumber(data[[var_name]])))) {
# Don't warn for NULL/NA, as different warnings are used for those
if (!isTRUE(any(is.na(data[[var_name]])))) {
warning("A non-integer value was supplied for '", var_name, "'!",
" It will be truncated to an integer.", call. = FALSE)
}
} else {
# Round before setting mode to integer to avoid floating point errors
data[[var_name]] <- round(data[[var_name]])
}
mode(data[[var_name]]) <- "integer"
} else {
# Round before setting mode to integer to avoid floating point errors
data[[var_name]] <- round(data[[var_name]])
mode(data[[var_name]]) <- "integer"
}
mode(data[[var_name]]) <- "integer"
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions tests/testthat/test-data.R
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,9 @@ test_that("process_data warns on int coercion", {
expect_no_warning(
process_data(list(a = c(1, 2, 3)), model_variables = mod$variables())
)
expect_no_warning(
process_data(list(a = factor(c("a", "b", "c"))), model_variables = mod$variables())
)
})

test_that("Floating-point differences do not cause truncation towards 0", {
Expand Down

0 comments on commit a45d4f7

Please sign in to comment.