From 13fc2a3e9d69a36646b99114fb8487dd67e2ec28 Mon Sep 17 00:00:00 2001 From: jgabry Date: Tue, 30 Dec 2025 13:54:15 -0700 Subject: [PATCH] Improve error message if any data is NULL fixes #1126 --- R/data.R | 8 +++++++- tests/testthat/test-data.R | 13 +++++++++++++ tests/testthat/test-json.R | 7 +++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/R/data.R b/R/data.R index f483ba4c2..31b647e2f 100644 --- a/R/data.R +++ b/R/data.R @@ -77,6 +77,9 @@ write_stan_json <- function(data, file, always_decimal = FALSE) { for (var_name in data_names) { var <- data[[var_name]] + if (is.null(var)) { + stop("Variable '", var_name, "' is NULL.", call. = FALSE) + } if (!(is.numeric(var) || is.factor(var) || is.logical(var) || is.data.frame(var) || is.list(var))) { stop("Variable '", var_name, "' is of invalid type.", call. = FALSE) @@ -176,7 +179,10 @@ process_data <- function(data, model_variables = NULL) { call. = FALSE ) } - for(var_name in names(data_variables)) { + for (var_name in names(data_variables)) { + if (is.null(data[[var_name]])) { + stop("Variable '", var_name, "' is NULL.", call. = FALSE) + } # distinguish between scalars and arrays/vectors of length 1 if (length(data[[var_name]]) == 1 && data_variables[[var_name]]$dimensions == 1) { diff --git a/tests/testthat/test-data.R b/tests/testthat/test-data.R index c7283d9bd..b024f5e6d 100644 --- a/tests/testthat/test-data.R +++ b/tests/testthat/test-data.R @@ -44,6 +44,19 @@ test_that("process_data works for inputs of length one", { expect_equal(jsonlite::read_json(process_data(data, model_variables = mod$variables())), list(val = list(5))) }) +test_that("process_data errors on NULL data variables", { + stan_file <- write_stan_file(" + data { + int N; + } + ") + mod <- cmdstan_model(stan_file, compile = FALSE) + expect_error( + process_data(list(N = NULL), model_variables = mod$variables()), + "Variable 'N' is NULL" + ) +}) + test_that("process_fitted_params() works with basic input types", { temp_file <- tempfile() temp_files <- c(tempfile(), diff --git a/tests/testthat/test-json.R b/tests/testthat/test-json.R index 1f7fb21b6..c2c2657cf 100644 --- a/tests/testthat/test-json.R +++ b/tests/testthat/test-json.R @@ -116,6 +116,13 @@ test_that("write_stan_json errors if NAs", { ) }) +test_that("write_stan_json errors if NULL variables", { + expect_error( + write_stan_json(list(N = NULL), tempfile()), + "Variable 'N' is NULL" + ) +}) + test_that("write_stan_json() errors if data is not a list", { expect_error( write_stan_json(1:10),