Nautica
Nautica

Reputation: 2018

Whole number in brackets gets coerced into unusual format in kable table in RMarkdown script

I have a basic dataframe/tibble shown as:

  Variable                  `Attended Patients` `Programme Average (Weighted Mean/%)`
  <chr>                     <chr>               <chr>                                
1 Less than 'O' level       17149 (56.7)        (56.9)                               
2 'O' level                 9419 (31.2)         (31)                                 
3 'A' level                 2821 (9.3)          (9.3)                                
4 University/college        680 (2.2)           (2.3)                                
5 University degree         132 (0.4)           (0.5)                                
6 Postgraduate/professional 26 (0.1)            (0.1)  

Which I want to visualise in an RMarkdown script. Through built-in RStudio viewer, the table looks fine with:

foo %>% knitr::kable() %>%
  kableExtra::kable_styling(c("striped", "condensed"), full_width = T) 

enter image description here

However when I then want to create the table in an RMarkdown script, the Programme Average value for the "O-level Variable" has its brackets removed and a decimal added to the end, which I can't ascertain why.

enter image description here

Sample RMarkdown script and table:

---
title: "Untitled"
output: html_document
---

```{r test, echo = F}
library(knitr)
library(tidyverse)
library(kableExtra)

foo <- structure(
  list(
    Variable = c(
      "Less than 'O' level", "'O' level", "'A' level", "University/college", "University degree", "Postgraduate/professional"),
    `Attended Patients` = c("17149 (56.7)", "9419 (31.2)", "2821 (9.3)", "680 (2.2)", "132 (0.4)", "26 (0.1)"),
    `Programme Average (Weighted Mean/%)` = c("(56.9)", "(31)", "(9.3)", "(2.3)", "(0.5)", "(0.1)")
  ),
  row.names = c(NA, -6L),
  class = c("tbl_df", "tbl", "data.frame")
)

foo %>% kable() %>%
  kable_styling(c("striped", "condensed"), full_width = T) 
```

Upvotes: 1

Views: 733

Answers (1)

user2554330
user2554330

Reputation: 44877

The problem is that (31) is one of the ways Pandoc Markdown uses to indicate an ordered list. To disable this, put these lines in your YAML header:

output: 
  html_document:
    md_extensions: "-fancy_lists"

This will mean you need to use the simple format for all ordered lists in your document, i.e. a number followed by a period.

Edited to add:

If you want to use the fancy list syntax elsewhere in the document, you can escape the parenthesis using a backslash (which would have to be a double backslash in an R string), e.g. "(31)" would become "\\(31)".

Upvotes: 3

Related Questions