R:格式化所有变量的双向制表,只改变一个

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

我想使用 janitor::tabyl 为数据中给定变量的每个变量创建双向制表。例如

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)

理想情况下,我希望使用 purrr:map 遍历所有其他变量,并针对 gender 进行上述制表。到目前为止,我已经在

之后创建了主要表格
humans %>%
  select_if(is.character) %>%
  select(-name, -gender) %>%
  imap(.f = ~janitor::tabyl(dat = humans, !!sym(.y), gender))

但是我无法将类似的逻辑应用于之前提供的 adorn_* 调用

有没有一种方法可以使用 purrr 来完成?

我认为 imap 调用也没有任何变化,您可以类似地通过管道 (%>%) 函数:

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)
#....