【发布时间】:2020-12-03 14:39:01
【问题描述】:
数据中带有 $-signs 的 knitr::kable 很困惑。显示的数据就好像它们应该处于数学模式一样。有趣的是,knitr to PDF 并没有显示出这种效果。
我尝试使用反斜杠转义美元符号(甚至尝试使用最多四个反斜杠),使用块选项“标记”来获取结果,在 kable 中设置自动转义,或者使用 Hex-Unicode而不是字符。没有任何帮助。 任何进一步的想法都非常欢迎。
我使用 Rstudio 来编织 HTML 或 PDF。这是我的 *.Rmd 中的 MWE:
---
title: MWE knitr::kable does not escape special character $ correctly in the string data when knitring to html (to PDF is okay)
output:
html_document:
df_print: paged
pdf_document: default
---
```{r UNESCAPED , eval=TRUE , echo=FALSE , tidy=TRUE, message=FALSE , warning=FALSE , results='asis'}
library ("knitr")
library("kableExtra")#not needed but helpful to see the problem
library("tidyverse")#not needed but helpful to see the problem
data <- data.frame(stringVar=c("$1$","$2$"))
#escaping $ shows error message:
#data <- data.frame(stringVar=c("\$1\$","\$2\$"))
if (knitr::is_html_output())
{
knitr::kable(data, row.names = TRUE, format = "html" , escape = TRUE)%>% #same effect with escape=FALSE
kable_styling( "striped")#same effect without kable_styling
#last cell is rendered in math mode
}else{
knitr::kable(data, format="latex", longtable=T, booktabs = T, linesep = "", row.names = TRUE, escape = TRUE) %>%
kable_styling(latex_options =c("striped"))
#last cell is rendered as expected
}#end of if
```
【问题讨论】:
-
如果使用 \ 转义:您需要一个转义美元符号,然后再转义第一个反斜杠。使用
data <- data.frame(stringVar=c("\\$1\\$","\\$2\\$"))似乎适用于 HTML 表格。 -
是的,你是对的。抱歉,我对替换的反斜杠数量感到困惑。 user12728748的解决方案很简单。
标签: html r knitr special-characters kable