r-markdownrstudioknitrkabletinytex

Knit a kable to PDF in RMarkdown that includes special characters in the table values


I'm trying to format a kable that includes the permyriad sign "‱". Permyriad means 1 out of every 10,000, so 1‱ = 0.01%.

I can get it to work with the special character σ, as in the screenshot and code below. Looking for a way to replace "σ" replaced with "‱".

kable with sigma, not permyriad

I am pretty sure that there exists a magical combination of the three variables what_should_this_be, should_i_escape_or_not, and id_like_to_use_booktabs that will do the trick.

I'm doing this within RStudio using the tinytex package.

Here's what I've attempted so far:

  1. The exact value for the variable what_should_this_be that results in knitting the ‱ sign in the final pdf. The Unicode value for "‱" is U+2031.

    Values I've tried:

    • Combinations of "\textperthousand" with varying numbers of escapes, with and without brackets, with and without opening & closing $
    • Copy-pasting the symbol directly with varying numbers of escapes
    • "\U2031" with varying numbers of escapes
  2. Various combinations with should_i_escape_or_not set to TRUE or FALSE.

  3. I'd like to use booktabs... but that might be asking a bit much, so I've tried various combinations setting id_like_to_use_booktabs to TRUE or FALSE.

  4. Various combinations of setting the "Typeset LaTeX into PDF using:" option in RStudio > Tools > Sweave

    ```{r, echo = FALSE}

    library(magrittr)

    what_should_this_be     <- "$\\sigma$"
    should_escape_or_not    <- FALSE
    id_like_to_use_booktabs <- TRUE

    knitr::kable(
      head(mtcars) %>%
        dplyr::select(mpg) %>%
        tibble::rownames_to_column("car") %>%
        dplyr::mutate(mpg = paste0(mpg, what_should_this_be)),
      align     = "cc",
      escape    = should_escape_or_not,
      booktabs  = id_like_to_use_booktabs,
      caption   = "Works with character $\\sigma$, but what about permyriad?"
    )

    ```

Solution

  • Could use the textcomp package and \textpertenthousand

    ---
    output:
      pdf_document:
        latex_engine: xelatex
    header-includes:
      - \usepackage{textcomp}
    ---
    
    ```{r, echo = FALSE}
      library(magrittr)
      what_should_this_be     <- "\\textpertenthousand"
    
      knitr::kable(
        head(mtcars) %>%
          dplyr::select(mpg) %>%
          tibble::rownames_to_column("car") %>%
          dplyr::mutate(mpg = paste0(mpg, what_should_this_be)),
        align     = "cc",
        escape    = F,
        booktabs  = T,
        caption   = "Works with character $\\sigma$, but what about permyriad?"
      )
    ```
    

    enter image description here