From 19651d1c6bfd59a7fee6f77ffd5da46b82b3d500 Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 9 Oct 2024 15:09:36 +0200 Subject: [PATCH] `include_reference = TRUE` not working when using `cut()` directly in model formula (#1026) Fixes #1025 --- R/utils_format.R | 14 ++++++++++++-- tests/testthat/test-pipe.R | 13 +++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/R/utils_format.R b/R/utils_format.R index 667e53895..d672d494a 100644 --- a/R/utils_format.R +++ b/R/utils_format.R @@ -371,13 +371,23 @@ # check if we have model data, else return parameter table if (is.null(model_data)) { - params + return(params) } # find factors and factor levels and check if we have any factors in the data factors <- .find_factor_levels(model_data, model, model_call = attributes(params)$model_call) if (!length(factors)) { - params + # in case of "on-the-fly" factors, e.g.: + # m <- lm(mpg ~ cut(wt, c(0, 2.5, 3, 5)), data = mtcars) + # we need to receive the data from the model frame, in order to find factors + model_data <- insight::get_data(model, source = "mf", verbose = FALSE) + if (!is.null(model_data)) { + factors <- .find_factor_levels(model_data, model, model_call = attributes(params)$model_call) + } + # if we still didn't find anything, quit... + if (!length(factors)) { + return(params) + } } # we need some more information about prettified labels etc. diff --git a/tests/testthat/test-pipe.R b/tests/testthat/test-pipe.R index ff8bd9953..b6502e11b 100644 --- a/tests/testthat/test-pipe.R +++ b/tests/testthat/test-pipe.R @@ -13,3 +13,16 @@ test_that("print in pipe", { "Species [setosa] | 0.00 | | | | " ) }) + +test_that("print in pipe, on-the-fly factor", { + data(mtcars) + out <- capture.output({ + mtcars |> + lm(mpg ~ cut(wt, c(0, 2.5, 3, 5)), data = _) |> + model_parameters(include_reference = TRUE) + }) + expect_identical( + out[4], + "cut(wt, c(0, 2.5, 3, 5)) [(0,2.5]] | 0.00 | | | | " + ) +})