From d771f2c7beda24cb9c9707e0f64493d6e48ddd10 Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 20 Nov 2024 12:30:25 +0100 Subject: [PATCH] find_transformation() returning multiple values Fixes #971 --- DESCRIPTION | 2 +- NEWS.md | 3 +++ R/find_transformation.R | 18 +++++++++++------- tests/testthat/test-find_transformation.R | 16 ++++++++++++++++ 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index c96200b09..101c6a53c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: insight Title: Easy Access to Model Information for Various Model Objects -Version: 0.99.0.15 +Version: 0.99.0.16 Authors@R: c(person(given = "Daniel", family = "Lüdecke", diff --git a/NEWS.md b/NEWS.md index 4a93c1eb6..27f5c7310 100644 --- a/NEWS.md +++ b/NEWS.md @@ -62,6 +62,9 @@ * Fixed issue in `compact_character()` and `compact_list()` for date-variables. +* Fixed edge case in `find_transformation()` for simple log-transformation of + the response variable. + # insight 0.20.5 ## General diff --git a/R/find_transformation.R b/R/find_transformation.R index f82cfb9eb..b3c0e26d4 100644 --- a/R/find_transformation.R +++ b/R/find_transformation.R @@ -102,15 +102,19 @@ find_transformation.character <- function(x, ...) { if (grepl("log\\(log\\((.*)\\)\\)", x)) { transform_fun <- "log-log" } else { - # 1. try: log(x + number) - plus_minus <- .safe( - eval(parse(text = gsub("log\\(([^,\\+)]*)(.*)\\)", "\\2", x))) - ) - # 2. try: log(number + x) - if (is.null(plus_minus)) { + plus_minus <- NULL + # make sure we definitly have a "+" in the log-transformation + if (grepl("+", x, fixed = TRUE)) { + # 1. try: log(x + number) plus_minus <- .safe( - eval(parse(text = gsub("log\\(([^,\\+)]*)(.*)\\)", "\\1", x))) + eval(parse(text = gsub("log\\(([^,\\+)]*)(.*)\\)", "\\2", x))) ) + # 2. try: log(number + x) + if (is.null(plus_minus)) { + plus_minus <- .safe( + eval(parse(text = gsub("log\\(([^,\\+)]*)(.*)\\)", "\\1", x))) + ) + } } if (is.null(plus_minus) || is.function(plus_minus)) { transform_fun <- "log" diff --git a/tests/testthat/test-find_transformation.R b/tests/testthat/test-find_transformation.R index f069cbe6c..4ee97378d 100644 --- a/tests/testthat/test-find_transformation.R +++ b/tests/testthat/test-find_transformation.R @@ -132,3 +132,19 @@ test_that("find_transformation - detect powers", { ) ) }) + + +test_that("find_transformation - works with log-edge cases", { + set.seed(1) + n <- 30 + x <- rlnorm(n = n, meanlog = 3, sdlog = 1) + y <- exp(2 + log(x) + rnorm(n, sd = 3)) + d <- data.frame(x, y) + m <- lm(log(y) ~ log(x), data = d) + + expect_identical(find_transformation(m), "log") + expect_identical( + find_transformation(m, include_all = TRUE), + list(response = c(y = "log"), conditional = c(x = "log")) + ) +})