Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 561
TinglTanglBob Avatar asked Aug 27 '18 10:08

TinglTanglBob


People also ask

What is “R Markdown”?

The document format “R Markdown” was first introduced in the knitr package ( Xie 2015, 2022b) in early 2012. The idea was to embed code chunks (of R or other languages) in Markdown documents.

How do I convert a markdown file to HTML in R?

Next, select “Markdown Quick Reference”. RStudio will open the Markdown Quick Reference guide in the Help pane. To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want.

What is a RMD file in Markdown?

.Rmd files are meant to contain text written in markdown. Markdown is a set of conventions for formatting plain text. You can use markdown to indicate bold and italic text lists headers (e.g., section titles) The conventions of markdown are very unobtrusive, which make Markdown files easy to read.

Do you have the skills to use R Markdown?

By the end, you’ll have the skills you need to produce a document or presentation using R Markdown, from scratch! We’ll show you how to convert the default R Markdown document into a useful reference guide of your own. We encourage you to follow along by building out your own R Markdown guide, but if you prefer to just read along, that works, too!


1 Answers

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.

like image 75
Stéphane Laurent Avatar answered Oct 08 '22 05:10

Stéphane Laurent