JRR
JRR

Reputation: 588

R: formatting two-way tabulations for all variables, only vary one

I would like to use janitor::tabyl to create two-way tabulations for every variable with respect a given variable in the data. For example

library(tidyverse)
library(janitor)
humans <- starwars %>%
    filter(species == "Human")
t2 <- humans %>%
    tabyl(gender, eye_color)

t2 %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting(digits = 2) %>%
  adorn_ns()
#>  gender       blue blue-gray       brown      dark      hazel    yellow
#>  female 33.33% (3) 0.00% (0) 55.56%  (5) 0.00% (0) 11.11% (1) 0.00% (0)
#>    male 34.62% (9) 3.85% (1) 46.15% (12) 3.85% (1)  3.85% (1) 7.69% (2)

I would ideally like to use purrr:map to iterate through every other variable and do the above tabulation with respect to gender. So far I have created the main tabulation following this post

humans %>%
  select_if(is.character) %>%
  select(-name, -gender) %>%
  imap(.f = ~janitor::tabyl(dat = humans, !!sym(.y), gender))

But I am having trouble applying a similar logic to the adorn_* calls previously provided

Is there a way that this can be done using purrr?

Upvotes: 1

Views: 121

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389155

I don't think anything changes in imap call as well, you can just pipe (%>%) the functions similarly :

library(janitor)
library(dplyr)

humans %>%
  select(where(is.character)) %>%
  select(-name, -gender) %>%
  purrr::imap(.f = ~tabyl(dat = humans, !!sym(.y), gender) %>%
                     adorn_percentages("row") %>%
                     adorn_pct_formatting(digits = 2) %>%
                     adorn_ns())

#$hair_color
#    hair_color    feminine   masculine
#        auburn 100.00% (1)   0.00% (0)
#  auburn, grey   0.00% (0) 100.00% (1)
# auburn, white   0.00% (0) 100.00% (1)
#         black  12.50% (1)  87.50% (7)
#         blond   0.00% (0) 100.00% (3)
#         brown  42.86% (6)  57.14% (8)
#   brown, grey   0.00% (0) 100.00% (1)
#          grey   0.00% (0) 100.00% (1)
#          none   0.00% (0) 100.00% (3)
#         white  50.00% (1)  50.00% (1)

#$skin_color
# skin_color   feminine    masculine
#       dark  0.00% (0) 100.00%  (4)
#       fair 18.75% (3)  81.25% (13)
#      light 54.55% (6)  45.45%  (5)
#       pale  0.00% (0) 100.00%  (1)
#        tan  0.00% (0) 100.00%  (2)
#      white  0.00% (0) 100.00%  (1)
#....

Upvotes: 2

Related Questions