编织到html时,knitr :: kable无法在字符串数据中正确转义特殊字符$可以使用PDF

问题描述

在数据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
    
    
```

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...