rmarkdown & kable / kableextra: печать символа% в таблице при использовании escape = F - PullRequest
0 голосов
/ 27 августа 2018

Я хочу создать таблицу в pdf-документе, используя rmarkdwon и kable. В заголовке должен быть перевод строки, поэтому для этого мне нужно установить escape = F. Сама таблица содержит значения процентов в виде строк, включая символ% (например, «13%»). Я нашел здесь https://tex.stackexchange.com/questions/34580/escape-character-in-latex, что% - это специальный символ в La (Tex), и я должен исключить его, используя \%. Но как я могу создать и сохранить строку "\%" в R? Я пробовал следующее, но у меня ничего не получалось:

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

Кто-нибудь знает решение этой проблемы?

Заранее спасибо

редактирование: Вот пример кода для моей проблемы:

редактирование редактирования: В моем составленном тестовом столе data.frame я забыл установить stringsAsFactors = F. Вот что послужило причиной различий с моими результатами реальных данных. Я добавил его в код и обновил выводимые картинки

    ---
    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")
    ```

Каким-то образом% -символ не отображается. Я понятия не имею, как это получается, так как я получил другую таблицу с тем же стилем (только без переноса строки), и% -символ отлично работает.

enter image description here

enter image description here

enter image description here

1 Ответ

0 голосов
/ 28 августа 2018

Используйте способ 2 с 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

Разве это не то, что вы хотите? В противном случае я не понимаю.

...