From 0f929247b37fb081673b783310cc5fac3ed5f976 Mon Sep 17 00:00:00 2001 From: Sam Firke Date: Wed, 1 Feb 2023 17:20:37 -0500 Subject: [PATCH] as_tabyl() retains tabyl_type attribute if input is a tabyl (#524) fix #523 by tweaking as_tabyl() --- NEWS.md | 2 ++ R/adorn_totals.R | 3 ++- R/as_and_untabyl.R | 11 +++++++---- tests/testthat/test-adorn-totals.R | 8 ++++++++ 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3d7e8c14..550b4698 100644 --- a/NEWS.md +++ b/NEWS.md @@ -63,6 +63,8 @@ These are all minor breaking changes resulting from enhancements and are not exp * `adorn_ns()` can act on a single-column data.frame input with custom Ns supplied if the variable to adorn is specified with `...` (#456). +* `adorn_totals()` on a one_way tabyl preserves the `tabyl_type` attribute so that a subsequent call to `adorn_pct_formatting()` works correctly on one-way tabyls (#523). + # janitor 2.1.0 (2021-01-05) ## New features diff --git a/R/adorn_totals.R b/R/adorn_totals.R index a09ac3e8..f1c36ce3 100644 --- a/R/adorn_totals.R +++ b/R/adorn_totals.R @@ -59,7 +59,8 @@ adorn_totals <- function(dat, where = "row", fill = "-", na.rm = TRUE, name = "T if ("grouped_df" %in% class(dat)) { dat <- dplyr::ungroup(dat) } - dat <- as_tabyl(dat) + + dat <- as_tabyl(dat) # even a tabyl needs to be recast as a tabyl to reset the core in case it's been sorted # set totals attribute if (sum(where %in% attr(dat, "totals")) > 0) { # if either of the values of "where" are already in totals attribute diff --git a/R/as_and_untabyl.R b/R/as_and_untabyl.R index c76cbb01..f73a91b4 100644 --- a/R/as_and_untabyl.R +++ b/R/as_and_untabyl.R @@ -47,10 +47,13 @@ as_tabyl <- function(dat, axes = 2, row_var_name = NULL, col_var_name = NULL) { attr(dat, "core") <- as.data.frame(dat) # core goes first so dat does not yet have attributes attached to it } - attr(dat, "tabyl_type") <- dplyr::case_when( - axes == 1 ~ "one_way", - axes == 2 ~ "two_way" - ) + attr(dat, "tabyl_type") <- ifelse( + !is.null(attr(dat, "tabyl_type")), + attr(dat, "tabyl_type"), # if a one_way tabyl has as_tabyl called on it, it should stay a one_way #523 + dplyr::case_when( + axes == 1 ~ "one_way", + axes == 2 ~ "two_way" + )) class(dat) <- c("tabyl", setdiff(class(dat), "tabyl")) if (!missing(row_var_name) | !missing(col_var_name)) { diff --git a/tests/testthat/test-adorn-totals.R b/tests/testthat/test-adorn-totals.R index 0c228ea2..eb5b91b4 100644 --- a/tests/testthat/test-adorn-totals.R +++ b/tests/testthat/test-adorn-totals.R @@ -401,6 +401,14 @@ test_that("supplying NA as fill still works with non-character first col and num expect_equal(test_df[1:3, 2:7], out[1:3,2:7], ignore_attr = TRUE) }) +test_that("one_way tabyl inputs retain that class", { + expect_equal( + attr(mtcars %>% tabyl(am) %>% adorn_totals("both"), "tabyl_type"), + "one_way" + ) +}) + + # Tests from #413, different values for row and col names test_that("long vectors are trimmed", { expect_equal(