diff --git a/R/facet-layout.r b/R/facet-layout.r index ef312b4a1..1f38aaf5e 100644 --- a/R/facet-layout.r +++ b/R/facet-layout.r @@ -95,6 +95,17 @@ layout_base <- function(data, vars = NULL, drop = TRUE) { # variables that appear in the data has_all <- unlist(plyr::llply(values, length)) == length(vars) if (!any(has_all)) { + vars_to_check <- vars[vars != "."] + all_data_vars <- unique(unlist(lapply(data, names))) + missing_vars <- setdiff(vars_to_check, all_data_vars) + if(length(missing_vars) > 0){ + stop(sprintf( + "Facet variable%s not found in data: %s\nAvailable columns: %s\nUse string notation like facet_wrap(\"var\") instead of formula notation facet_wrap(. ~ var)", + if(length(missing_vars) > 1) "s" else "", + paste(missing_vars, collapse = ", "), + paste(all_data_vars, collapse = ", ") + )) + } stop("At least one layer must contain all variables used for facetting") } diff --git a/R/z_animintHelpers.R b/R/z_animintHelpers.R index 97cce5a7f..39d39f291 100644 --- a/R/z_animintHelpers.R +++ b/R/z_animintHelpers.R @@ -1082,3 +1082,5 @@ selectSSandCS <- function(aesthetics_list){ ## TODO: how to handle showSelected$ignored in prev animint code?? return(aes.list) } + + diff --git a/tests/testthat/test-renderer-facet-error-messages.R b/tests/testthat/test-renderer-facet-error-messages.R new file mode 100644 index 000000000..79be2d002 --- /dev/null +++ b/tests/testthat/test-renderer-facet-error-messages.R @@ -0,0 +1,34 @@ +acontext("Facet error messages") +test_that("facet_wrap formula with missing variable gives clear error", { + viz <- list( + scatter = ggplot() + + facet_wrap(. ~ NonExistentColumn) + + geom_point(aes(Sepal.Length, Petal.Length), data = iris) + ) + expect_error( + animint2dir(viz, out.dir = tempfile(), open.browser = FALSE), + "Facet variable not found in data: NonExistentColumn\nAvailable columns: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species\nUse string notation like facet_wrap(\"var\") instead of formula notation facet_wrap(. ~ var)", + fixed = TRUE + ) +}) +test_that("facet_grid formula with missing variable gives clear error", { + viz <- list( + scatter = ggplot() + + facet_grid(. ~ MissingVar) + + geom_point(aes(Sepal.Length, Petal.Length), data = iris) + ) + expect_error( + animint2dir(viz, out.dir = tempfile(), open.browser = FALSE), + "Facet variable not found in data: MissingVar\nAvailable columns: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species\nUse string notation like facet_wrap(\"var\") instead of formula notation facet_wrap(. ~ var)", + fixed = TRUE + ) +}) +test_that("facet_wrap string notation works", { + viz <- list( + scatter = ggplot() + + facet_wrap("Species") + + geom_point(aes(Sepal.Length, Petal.Length), data = iris) + ) + info <- animint2dir(viz, out.dir = tempfile(), open.browser = FALSE) + expect_true(file.exists(file.path(info$out.dir, "index.html"))) +})