Search code examples
rdplyrtidyversecontingencyjanitor

Two-Way Contingency Table with frequencies and percentages


I got the following Two-way contingency table with cell percentages along with frequencies (in parentheses).

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)

The R code I used is

library(dplyr)

library(janitor)

starwars %>%
  filter(species == "Human") %>% 
  tabyl(gender, eye_color) %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting(digits = 2) %>%
  adorn_ns()

However, I want to get the same kind of table with cell frequencies along with percentages (in parentheses). Any help, please.


Solution

  • We can change the position argument in adorn_ns from rear (default) to front

    library(tidyverse)
    starwars %>%
      filter(species == "Human") %>% 
       tabyl(gender, eye_color) %>%
       adorn_percentages("row") %>%
       adorn_pct_formatting(digits = 2) %>%
       adorn_ns(position = "front")
    # gender       blue blue-gray       brown      dark      hazel    yellow
    # female 3 (33.33%) 0 (0.00%)  5 (55.56%) 0 (0.00%) 1 (11.11%) 0 (0.00%)
    #   male 9 (34.62%) 1 (3.85%) 12 (46.15%) 1 (3.85%) 1  (3.85%) 2 (7.69%)
    

    Or another option if the object is already created would be post-processswith mutate_at to change the formatting of all the columns except the first by capturing the characters in two blocks, reverse the positions by reversing the backreference while adding () for the percentage

    library(tidyverse)
    starwars %>%
      filter(species == "Human") %>% 
      tabyl(gender, eye_color) %>%
      adorn_percentages("row") %>%
      adorn_pct_formatting(digits = 2) %>%
      adorn_ns() %>% 
      mutate_at(-1, list(~ str_replace(., "^([0-9.%]+)\\s+\\((\\d+)\\)", "\\2 (\\1)")))
    # gender       blue blue-gray       brown      dark      hazel    yellow
    #1 female 3 (33.33%) 0 (0.00%)  5 (55.56%) 0 (0.00%) 1 (11.11%) 0 (0.00%)
    #2   male 9 (34.62%) 1 (3.85%) 12 (46.15%) 1 (3.85%)  1 (3.85%) 2 (7.69%)