rmarkdown & kable/kableextra: Printing % symbol in Table when using escape = F
Asked Answered
B

2

7

I want to create a table in a pdf-document using rmarkdwon and kable. In the header there has to be a linebreak, so to do so i need to set escape = F. The table itself contains percent-values as strings including the % symbol (for example: "13%"). I found here https://tex.stackexchange.com/questions/34580/escape-character-in-latex that % is a special character in La(Tex) and i have to exclude it using \%. But how can i create and store a string "\%" in R? I've tried the following but nothing worked for me:

gsub("%", "\%", c("14%", "15%", "16%"))
Error: '\%' is an unrecognized escape in character string starting ""\%"

gsub("%", "\\%", c("14%", "15%", "16%"))
[1] "14%" "15%" "16%"

> cat("\\%")
\%

gsub("%", cat("\\%"), c("14%", "15%", "16%"))
\%
Error in gsub("%", cat("\\%"), c("14%", "15%", "16%")) : 
  invalid 'replacement' argument

Does anybody know the solution for this problem?

Thanks in advance

edit: Here is some example code for my problem:

edit of the edit: in my made up data.frame testtable i forgot to set stringsAsFactors = F. Thats what caused the differences to my real-data results. I've added it to the code and updated the output-pictures

    ---
    title: "Table with % and linbebreak"
    output:
      # html_document: default
      pdf_document:
        keep_tex: yes
      fig_caption: yes
    lang: de
    ---


    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE, warning = FALSE, error = FALSE, dev=c('pdf','png'), dpi=500)

    library(dplyr)
    library(data.table)
    library(reshape2)
    library(knitr)
    library(markdown)
    library(kableExtra)
    library(psych)
    library(survey)
    library(ggplot2)

    set.seed(123)
    testtable = data.frame(matrix(paste0(sample(1:100,16, replace = T), "%"), nrow = 4, byrow = T), stringsAsFactors = F)
    testtable$group = c("Var1", "Var2", "Var3", "Var4")
    testtable = testtable[c(5,1:4)]
    colnames(testtable) = c("Variable","All\n(n = 300)", "Group1\n(n = 120)", "Group2\n(n = 100)", "Group3\n(n = 80)")

    ```
    # Table including %-symbol, escape=F not set

    ```{r}
    testtable %>% mutate_all(linebreak) %>% 
    kable(format = "latex", align = c("l", "c", "c", "c", "c"), caption = "Caption", booktabs = T, col.names = linebreak(names(testtable), align = "c")) %>%
      kable_styling(position = "center", latex_options = c("hold_position")) %>%
      footnote(general = "* This is a note to show what * shows in this table plus some addidtional words to make this string a bit longer. Still a bit more", threeparttable = T, general_title = "Anmerkung:", title_format = "italic")
    ```

    # Table including %-symbol, escape=F
    This leads to an Error, see pic below

    ```{r}
    testtable %>% mutate_all(linebreak) %>% 
    kable(format = "latex", align = c("l", "c", "c", "c", "c"), caption = "Caption", booktabs = T, escape = F, col.names = linebreak(names(testtable), align = "c")) %>%
      kable_styling(position = "center", latex_options = c("hold_position")) %>%
      footnote(general = "* This is a note to show what * shows in this table plus some addidtional words to make this string a bit longer. Still a bit more", threeparttable = T, general_title = "Anmerkung:", title_format = "italic")
    ```

    # Table without %-symbol, escape=F set

    ```{r}
    # removing the %
    testtable[,2:5] = apply(testtable[,2:5],2,function(f) gsub("%", "", f))

    testtable %>% mutate_all(linebreak) %>% 
    kable(format = "latex", align = c("l", "c", "c", "c", "c"), caption = "Caption", booktabs = T, escape = F, col.names = linebreak(names(testtable), align = "c")) %>%
      kable_styling(position = "center", latex_options = c("hold_position")) %>%
      footnote(general = "* This is a note to show what * shows in this table plus some addidtional words to make this string a bit longer. Still a bit more", threeparttable = T, general_title = "Anmerkung:", title_format = "italic")
    ```

Somehow %-symbol does not get displayed. I have no idea how it comes, since i got other table of the same style (just without a linebreak) and the %-symbol works great.

enter image description here

enter image description here

enter image description here

Banshee answered 27/8, 2018 at 10:11 Comment(6)
Could you post your table ? (or a part of it)Satsuma
@StéphaneLaurent i've added some made up data to my post. If neccessary i can add a little part of the real data later tooBanshee
That does not work with 29\\% ?Satsuma
@StéphaneLaurent, i had to re-edit my post once more, because i forgott to add the stringsAsFactors = F agrument. Now i get the same error in both test-data and my actual data. \\% unfortunately doesn't work for me, but maybe im doing something wrong. I used the following command: testtable[2:5] = apply(testtable[2:5], 2, function(f) gsub("%", "\\%", f)).Banshee
What about gsub("%", "\\\\%", f))? (four backslashes)Satsuma
Unfortunately the four backslashes lead to the same result as 2 :(Banshee
S
10

Use way 2 with gsub("%", "\\\\%", f)).

---
title: "Untitled"
author: "Stéphane Laurent"
date: "28 août 2018"
output: 
  pdf_document: 
    keep_tex: yes
editor_options: 
  chunk_output_type: console
---


```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE, warning = FALSE, error = FALSE, dev=c('pdf','png'), dpi=500)

    library(dplyr)
    library(data.table)
    library(reshape2)
    library(knitr)
    library(markdown)
    library(kableExtra)
    library(psych)
    library(survey)
    library(ggplot2)

    set.seed(123)
    testtable = data.frame(matrix(paste0(sample(1:100,16, replace = T), "%"), nrow = 4, byrow = T), stringsAsFactors = F)
    testtable$group = c("Var1", "Var2", "Var3", "Var4")
    testtable = testtable[c(5,1:4)]
    colnames(testtable) = c("Variable","All\n(n = 300)", "Group1\n(n = 120)", "Group2\n(n = 100)", "Group3\n(n = 80)")
```

# Table including %-symbol, escape=F not set

```{r}
    testtable %>% mutate_all(linebreak) %>% 
    kable(format = "latex", align = c("l", "c", "c", "c", "c"), caption = "Caption", booktabs = T, col.names = linebreak(names(testtable), align = "c")) %>%
      kable_styling(position = "center", latex_options = c("hold_position")) %>%
      footnote(general = "* This is a note to show what * shows in this table plus some addidtional words to make this string a bit longer. Still a bit more", threeparttable = T, general_title = "Anmerkung:", title_format = "italic")
```


# Table including %-symbol, escape=F

    This leads to an Error, see pic below

```{r}
testtable[,2:5] = apply(testtable[,2:5],2,function(f) gsub("%", "\\\\%", f))
    testtable %>% mutate_all(linebreak) %>% 
    kable(format = "latex", align = c("l", "c", "c", "c", "c"), caption = "Caption", booktabs = T, escape = F, col.names = linebreak(names(testtable), align = "c")) %>%
      kable_styling(position = "center", latex_options = c("hold_position")) %>%
      footnote(general = "* This is a note to show what * shows in this table plus some addidtional words to make this string a bit longer. Still a bit more", threeparttable = T, general_title = "Anmerkung:", title_format = "italic")
```

enter image description here

Isnt'it what you want? Otherwise I don't understand.

Smegma answered 28/8, 2018 at 11:16 Comment(2)
This is perfectly what i want! I will try it out as soon as i have access to the data and will accept your answer afterwards. Thanks a lot for your help!Banshee
Also thanks to you. I didn't know the linebreak command. So far I used a home-made way to split some cells.Satsuma
R
0

Another solution is to include the percent sign (or any other string of characters including characters you do want to escape) through custom LaTex commands defined before running kable.

```{r}
library(kableExtra)
library(tidyverse)
```

```{r}
test <- tibble(perc = c('4\\Perc', '34.2\\Perc'),
               bla = c('bla','blabla'),
               otherLatexCommand = c('\\RA', '\\RA'))
```

\newcommand\Perc{\%}
\newcommand\RA{$\Rightarrow$}

```{r}
test %>% kable('latex', escape=F)
```
Rhody answered 7/12, 2022 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.