Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 491
ludo Avatar asked Dec 23 '22 17:12

ludo


2 Answers

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

like image 107
Wimpel Avatar answered Jan 02 '23 08:01

Wimpel


I think the package summarytools can produce the desired output. Using your fakeData:

library(summarytools)
print(ctable(x = fakeData$gender, y = fakeData$bmi, prop = "t"),
      method = "render")

enter image description here

like image 31
momenezes Avatar answered Jan 02 '23 10:01

momenezes