Formatting and totals issue when using tabyl() with adorn_*() and qflextable()

Hello everyone, I am working on summarising surveillance data by district as part of a reporting workflow. I want to:

  • Count cases by district

  • Sort in descending order

  • Add a totals row

  • Format percentages

  • Convert the table to a qflextable() for reporting

Here is the code I am using:

library(janitor)
library(dplyr)
library(qflextable)

surv %>%
  tabyl(district, show_na = FALSE) %>%
  arrange(-n) %>%
  adorn_totals() %>%
  adorn_pct_formatting(digits = 2) %>%
  qflextable()

When I apply both sorting and formatting before converting to qflextable, I sometimes get:

  • A warning or error message

  • Percent formatting not applying to the totals row

What I have tried:

  • Checked the Epi R Handbook section on tabyl()

  • Reviewed StackOverflow threads about adorn_*() function ordering

  • Attempted changing the order of adorn_totals() and adorn_pct_formatting()

Still unsure what the recommended order should be so everything displays correctly.

Hey abhishek!

Nice clean workflow, you’re already using the {janitor} pipeline correctly.

The main issue is that {janitor}’s adorn_*() functions expect a specific order. The recommended sequence for your use case is:

  1. tabyl()

  2. (optional) arrange()

  3. adorn_totals()

  4. adorn_pct_formatting()

  5. then convert to qflextable()

That ensures adorn_pct_formatting() knows how to treat the totals row properly. If you format first, the totals cell may be converted to character and later cause a warning.

Try this:

library(janitor)
library(dplyr)
library(qflextable)

surv %>%
  tabyl(district, show_na = FALSE) %>%
  arrange(desc(n)) %>%                     # sort first
  adorn_totals("row") %>%                  # then totals
  adorn_pct_formatting(digits = 2) %>%     # then format
  qflextable()

You should get this, with the percent formatting applied to 100.00%.

  • Call adorn_totals() before adorn_pct_formatting().

  • Sorting can happen anywhere before totals/formatting.

  • If your total row shows % formatting errors, make sure the first argument to adorn_totals() is "row" and not "col".

You can confirm the correct order in ?adorn_totals, the examples there show totals applied first, formatting last.

Best,

Luis