gforge / Gmisc

An R package for creating tables, some plots and other useful utilities too small to merit their own package
49 stars 14 forks source link

show_all_values=T doen'st work for getDescriptionStatsBy #61

Closed peterolejua closed 2 years ago

peterolejua commented 3 years ago

Hello,

I have some factors with some categories with 0 counts. How can I make describeFactors to show all values including 0's

Thanks

gforge commented 3 years ago

Could you write up a quick test and so I can have a look at this?

gforge commented 2 years ago

Wrote up a test and it works just as expected, note that descibeFactors is unaffected by this. It is assumed that dropping an empty factor is so easy that it is not the job of the function to clean empty values.

test_that("Factors with 0 observations should be reported when show_all_values=TRUE, issue #61", {
  set.seed(1)
  n = 20
  d <- data.frame(single = sample(LETTERS[1], size = n, replace = TRUE),
                  two = sample(LETTERS[1:2], size = n, replace = TRUE),
                  three = sample(LETTERS[1:3], size = n, replace = TRUE),
                  by = sample(letters[1:2], size = n, replace = TRUE)) %>%
    mutate(across(everything(), function(x) factor(x, levels = c(unique(x), "no observation"))))

  out <- d %>%
    getDescriptionStatsBy(single,
                          two,
                          three,
                          by = by,
                          show_all_values = TRUE)
  expect_true(all(sapply(out, function(x) "no observation" %in% rownames(x))))

  out <- d %>%
    getDescriptionStatsBy(single,
                          two,
                          three,
                          by = by,
                          show_all_values = FALSE)
  expect_false("no observation" %in% rownames(out[[1]]))
  expect_true(all(sapply(out[2:3], function(x) "no observation" %in% rownames(x))))
})