Search code examples
rr-markdownmarkdowncrosstab

Cross Tabulation with R Markdown


I have struggle creating a simple nice looking cross tabulation for a PDF knitted R Markdown document. I have a data set that is similar to this example:

library(tidyverse)
fakeData <- tibble(id = c(1,2,3,4,5,6,7,8,9,10),
                   bmi = c("normal", "overweighted", "underweighted", "normal", "normal", "overweighted",
                           "normal", "overweighted", "underweighted","normal"),
                   gender = c("M", "F", "M", "M", "F", "F", "M", "F", "F", "F"))

I want to get an output like this one:

Desired output

Have anyone a trick/ a known good package to do this? Thanks a lot!


Solution

  • I think the janitor-package can help you out here...

    note: the percentages in the 'total' column do not match your desired output... That is because you are mixing colwise and rowwise percentage calculation in your output.. Is that really what you want?

    library( janitor )
    
    fakeTable <- fakeData %>% 
      tabyl( gender, bmi ) %>% 
      adorn_totals( where = c("row", "col") ) %>%
      adorn_percentages("row") %>%
      adorn_pct_formatting() %>%
      adorn_ns( position = "front" ) %>%
      adorn_title("combined")
    
    # gender/bmi    normal overweighted underweighted       Total
    #          F 2 (33.3%)    3 (50.0%)     1 (16.7%)  6 (100.0%)
    #          M 3 (75.0%)    0  (0.0%)     1 (25.0%)  4 (100.0%)
    #      Total 5 (50.0%)    3 (30.0%)     2 (20.0%) 10 (100.0%)
    

    knitted

    library(knitr)
    library(kableExtra)
    fakeTable %>%
      kable() %>%
      kable_styling(bootstrap_options = c("condensed", "striped", "bordered")) 
    

    enter image description here