5

I am trying to produce a well formatted contingency table in an rmarkdonw html document. Here is the code:

---
title: "Probabilidad"
author: "Nicolás Molano Gonzalez"
date: "7 de Abril de 2020"
output:
  html_document:
  fig_caption: true
---

```{r echo=F, message = FALSE, warning =F}

library(tidyverse)
library(kableExtra)
library(knitr)

set.seed(150)

```

this the data for the table:

```{r echo=FALSE, results = 'asis'}

ca_ctr_r<-.3

n   <- 250
nCA <- round(n*ca_ctr_r)
z0  <- data.frame(status=c(rep("CA",nCA),rep("CTR",n-nCA)))
z0$exposition <- NA
exp_CA  <- .45
exp_CTR <- .19

z0[z0$status %in% "CA","exposition"]  <- ifelse(runif(nCA) < exp_CA,"yes","no")
z0[z0$status %in% "CTR","exposition"] <- ifelse(runif(n-nCA) < exp_CA,"yes","no")

z0$exposition <- factor(z0$exposition,levels = c("yes","no"))

```

here is the code to print the contingency table, which should be improved.

```{r echo=FALSE, results = 'asis'}

res  <- kable(t(table(z0)%>%addmargins))
#res <- kable(t(table(z0)))
kable_styling(res,"striped", position = "center",full_width = F) %>% add_header_above(c("exposition","status"=2," "))

```

I want the output of the code to be similar to that of base R namely:

          status
exposition  CA CTR Sum
       no   40  96 136
       yes  35  79 114
       Sum  75 175 250

add_header_above lets me get the title for the columns but I am struggling to achieve the title for the rows (exposition) in the right position.

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
Nicolas Molano
  • 693
  • 4
  • 15

1 Answers1

1

I tried a workaround by explicitly adding a column to the left of the table before passing it to kable.

library(tidyverse)
library(kableExtra) 
library(knitr)

cont.table = mtcars %>% select(gear, carb) %>% 
    group_by_all() %>% tally() %>% 
    spread(key = gear, value = n)

cont.table %>% 
    rename("\t" = carb) %>% 
    add_column(" " = c("carb", rep(" ", nrow(.) - 1)), .before = "\t") %>% 
    kable() %>% 
    kable_styling(position = "left", full_width = F, ) %>% 
    add_header_above(c("", "", "gear", rep(" ", ncol(cont.table) - 2))) %>% 
    column_spec(1:2, bold = TRUE)