From c326e44bd52e4ec614d6236ed3f3ec56a1b926c3 Mon Sep 17 00:00:00 2001 From: Sam Firke Date: Sun, 19 Mar 2017 10:54:18 -0400 Subject: [PATCH] add_totals works on grouped_df closes #97 --- R/add_totals.R | 3 ++- tests/testthat/test-add-totals.R | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/R/add_totals.R b/R/add_totals.R index 01788f1c..6f8a4c51 100644 --- a/R/add_totals.R +++ b/R/add_totals.R @@ -17,7 +17,8 @@ add_totals <- function(dat, which = c("row", "col"), fill = "-", na.rm = TRUE){ - # clean_dat <- clean_names(dat) # bad names will make select_if choke + if("grouped_df" %in% class(dat)){ dat <- dplyr::ungroup(dat) } # grouped_df causes problems, #97 + dat[[1]] <- as.character(dat[[1]]) # for type matching when binding the word "Total" on a factor. Moved up to this line so that if only 1st col is numeric, the function errors if(sum(unlist(lapply(dat, is.numeric))) == 0){stop("data.frame must contain at least one column of class numeric")} diff --git a/tests/testthat/test-add-totals.R b/tests/testthat/test-add-totals.R index fecc69a7..24c52161 100644 --- a/tests/testthat/test-add-totals.R +++ b/tests/testthat/test-add-totals.R @@ -92,6 +92,13 @@ test_that("numeric first column is ignored", { stringsAsFactors = FALSE)) }) +test_that("grouped_df gets ungrouped and succeeds", { + ct <- mtcars %>% group_by(cyl, gear) %>% tally() %>% tidyr::spread(gear, n) + expect_equal(ct %>% add_totals(), + ct %>% ungroup() %>% add_totals + ) +}) + test_that("na.rm value gets passed through", { })