sfirke/janitor

Keep n columns when adorning percentages with > 1 variable

mvanaman opened this issue · 2 comments

Would be cool if when you're working with more than one variable, there is an option such as drop_Ns = or something so that when using adorn_percentages(), you get both Ns and percentages in the same way as when you do when working with only one variable. When there's two variables, you have to repeat yourself and use a left_join() to get equivalent output:

suppressMessages(library(janitor))
library(tidyverse)
# With One Variable
tabyl(mtcars, var1 = am)
 am  n percent
  0 19 0.59375
  1 13 0.40625

# With Two Variables
## Get the Ns
(Ns_Two_Variables <- tabyl(mtcars, var1 = am, var2 = cyl))
 am 4 6  8
  0 3 4 12
  1 8 3  2
## Get the Percentages
(Percentages_Two_Variables <- tabyl(mtcars, var1 = am, var2 = cyl) %>% adorn_percentages())
 am         4         6         8
  0 0.1578947 0.2105263 0.6315789
  1 0.6153846 0.2307692 0.1538462
## Join Them
left_join(
    Ns_Two_Variables,
    Percentages_Two_Variables,
    by = "am",
    suffix = c("_N", "_Percentage")
)
 am 4_N 6_N 8_N 4_Percentage 6_Percentage 8_Percentage
  0   3   4  12    0.1578947    0.2105263    0.6315789
  1   8   3   2    0.6153846    0.2307692    0.1538462

Created on 2022-12-07 with reprex v2.0.2

Hello, thanks for the suggestion. This feels too specialized to me to create a new argument for, but if there's widespread demand for this in comments over time maybe I would reconsider. In the meantime, here's a slightly shorter version of your solution that does not involve saving intermediate objects:

tabyl(mtcars, am, cyl) %>%
  left_join(adorn_percentages(.),
            by = "am",
            suffix = c("_N", "_Percentage"))

Understandable! I appreciate you taking a look at it. Thank you also for this solution, I hadn't thought of that!