From 42209347ad3e390cad4f73cdcbd6e7183f173078 Mon Sep 17 00:00:00 2001 From: Hadley Wickham Date: Fri, 28 Feb 2020 11:55:45 -0600 Subject: [PATCH] Don't convert implicit NA to explicit in fct_count Requiring some gymnastics to do the counting correctly :|. Fixes #151 --- NEWS.md | 2 ++ R/count.R | 8 ++++---- tests/testthat/test-count.R | 3 ++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3ddcf08d..468b598c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # forcats (development version) +* `fct_count()` no longer converts implicit NAs into explicit NAs (#151). + * `fct_inseq()` behaves more robustly when factor levels aren't all numbers (#221). diff --git a/R/count.R b/R/count.R index ffce6eee..cbdc6389 100644 --- a/R/count.R +++ b/R/count.R @@ -13,12 +13,12 @@ #' fct_count(f, sort = TRUE) #' fct_count(f, sort = TRUE, prop = TRUE) fct_count <- function(f, sort = FALSE, prop = FALSE) { - f <- check_factor(f) - f2 <- addNA(f, ifany = TRUE) + f2 <- check_factor(f) + n_na <- sum(is.na(f)) df <- tibble::tibble( - f = fct_unique(f2), - n = as.integer(table(f2)) + f = fct_inorder(c(levels(f2), if (n_na > 0) NA)), + n = c(tabulate(f2), if (n_na > 0) n_na) ) if (sort) { diff --git a/tests/testthat/test-count.R b/tests/testthat/test-count.R index ec83b611..53dd247a 100644 --- a/tests/testthat/test-count.R +++ b/tests/testthat/test-count.R @@ -7,12 +7,13 @@ test_that("0 count for empty levels", { expect_equal(out$n, c(0, 0)) }) - test_that("counts NA even when not in levels", { f <- factor(c("a", "a", NA)) out <- fct_count(f) expect_equal(out$n, c(2, 1)) + # and doesn't change levels + expect_equal(levels(out$f), levels(f)) }) test_that("returns marginal table", {