问题描述
在数据knitr :: kable中使用$符号感到困惑。数据显示为仿佛它们处于数学模式。有趣的是,编织到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 = "",escape = TRUE) %>%
kable_styling(latex_options =c("striped"))
#last cell is rendered as expected
}#end of if
```
解决方法
我可以使用反引号使它起作用:
编辑:
@aosmith是正确的-两次转义是更好的答案,因为它不会使用背景阴影进行渲染
---
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$"))
if (knitr::is_html_output())
{
# data %>% mutate_all( stringr::str_replace_all,pattern=fixed("$"),replacement="`$`") %>%
data %>% mutate_all( stringr::str_replace_all,replacement="\\$") %>%
knitr::kable( row.names = TRUE,format = "html",escape = FALSE) %>% #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
```