From 9a441a7d4ec26e49c0a0752504be1dd2c962042f Mon Sep 17 00:00:00 2001 From: Sam Firke Date: Mon, 17 Apr 2017 16:27:07 -0400 Subject: [PATCH] tabyl() does not call left_join() due to breaking changes in dplyr 0.6.0 NA no longer joined to NA. Closes #111 --- R/tabyl.R | 7 ++++++- tests/testthat/test-tabyl.R | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/R/tabyl.R b/R/tabyl.R index 74e523e7..22346ad5 100644 --- a/R/tabyl.R +++ b/R/tabyl.R @@ -59,7 +59,12 @@ tabyl.default <- function(vec, sort = FALSE, show_na = TRUE, ...) { result <- dat %>% dplyr::count(vec, sort = sort) if(is.factor(vec)){ - result <- tidyr::complete(result, vec) + expanded <- tidyr::expand(result, vec) + result <- merge(x = expanded, # can't use dplyr::left_join because as of 0.6.0, NAs don't match, and na_matches argument not present < 0.6.0 + y = result, + by = "vec", + all.x = TRUE) + result <- dplyr::arrange(result, vec) # restore sorting by factor level if(sort){result <- dplyr::arrange(result, dplyr::desc(n))} # undo reorder caused by complete() } diff --git a/tests/testthat/test-tabyl.R b/tests/testthat/test-tabyl.R index 6e942258..fc60757e 100644 --- a/tests/testthat/test-tabyl.R +++ b/tests/testthat/test-tabyl.R @@ -37,7 +37,7 @@ test_that("show_NA = FALSE parameter works", { tabyl(test_df_na$grp, show_na = FALSE)) }) -test_that("sorting is preserved for factors", { +test_that("ordering of result by factor levels is preserved for factors", { expect_equal(tabyl(factor(c("x", "y", "z"), levels = c("y", "z", "x")))[[1]], factor(c("y", "z", "x"), levels = c("y", "z", "x"))) })