html - 有没有一种方法可以确保在 print 语句中使用 kable 表时 unicode 符

当使用 print 显示 kable 时,将 kable 表格编织成 html 时,我无法显示 unicode 符号。注意 - 我需要在 print 语句中使用 kable 以遍历多个站点(kable 似乎无法在不使用 print 的情况下循环工作)。

当直接在 Rstudio 控制台中查看 kable 表时,unicode 符号显示正确,而当不使用 knit 显示时 knit。

当与 print 一起显示时,它会在控制台中正确显示,但在 knit 时则不会。看起来(在 html 检查器中,unicode 字符在编织时被转换为 <..>。

我有:

  • 包含为 results='asis'
  • 在 kable() 中使用了 escape=FALSE
  • 在我的表格中使用了等同于 U+2190 的 html(例如“↑”)

    #----

     title: "Example of Unicode symbols with kable and print"
     output: html_document
     #----
    
    #```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    #```
    
    
    #```{r dataset, , include=FALSE}
    library(tidyr)
    library(kableExtra)
    library(purrr)
    
    dat <- tibble(Symbol=c("up arrow", "down arrow", "side arrows"), 
                 htmlCode = c("&#8593;", "&#8595;", "&#8596;"))
    
    #```
    
    
    #```{r kable-tbl, results='asis'}
    tbl_fun <- function(df){
      tbl <- df %>%  kable(escape = F) %>%
      kable_styling(bootstrap_options = c("hover", "condensed"), 
                    full_width = F,  position = "left", fixed_thead = T)
    
      tbl
    }
    
    #this works when knit and when run in Rstudio console directly
    tbl_fun(dat)
    
    #when wrapped in a print function it works when run in Rstudio console directly 
    #but not when knit to html
    print_kable <- function(df) {
            tbl_fun(dat) %>%
                print(format = 'html')
    }
    
    print_kable(dat)
    
    
    #The above was a simplification - in my code I eventually want to iterate over 
    #many parameters, which is why I need to wrap in a print statement....
    #walk(.x = unique(dat$Site), print_kable)
    #```
    

最佳答案

是的,好像kable_styling()正在转义 html 实体。

我发现规避这种行为的方法是将我的 html 实体编码为其他东西,然后在完成所有格式设置后,用有效代码替换它们。

我可能会例如代码 &darr;作为@darr@ .

然后在管道的尽头,我执行以下操作:

kable(...) %>%
    kable_styling(...) %>%
    gsub("@darr@", "&darr;", .) %>%
    cat()

它对我有用。

我还想到了一个更通用的解决方案,我可以将任何 html 实体编码为 &<code>.然后这样替换它:

kable(...) %>%
    kable_styling(...) %>%
    gsub("&([^.]+).", "&\\1;", .) %>%
    cat()

但是,这是行不通的。它将打印 &darr; (或任何其他因替换而结束的 html 实体),从字面上看。似乎在第一种情况下,由于代码中明确提到了“&darr;”,因此可以这样理解。在后一种尝试中,由于它是动态生成的,因此在我们到达这里之前已经运行的 markdown 解析器无法识别它。

就我所知了。也许通过更多的研究,可以找到更通用的解决方案。

关于html - 有没有一种方法可以确保在 print 语句中使用 kable 表时 unicode 符号可见 - 当编织到 html 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58069545/

相关文章:

python - 未绑定(bind)的 super 对象,super(self, self)

keras - 卷积自动编码器keras的高损失

batch-file - Windows CMD 行 'sftp' 使用密码进行身份验证

r - 如何更新 R shiny 中 for 循环内的无功输出

php - 如何在 PHP 中使用 Google 我的业务 API 发布问题的新答案

azure-sql-database - 目前无法检索该地区的定价配置数据。请重试

c# - 配置生成器 - 无法加载程序集 - .Net Framework

laravel-5 - Phpspreadsheet 四舍五入帐号并从开始删除 0

amazon-web-services - 调用端点 url 时找不到 AWS API Gatewa

.net - ML .Net 无法重新训练神经网络