【问题标题】:r knitr - embedded HTML tags being escaped - how to turn offr knitr - 嵌入的 HTML 标签被转义 - 如何关闭
【发布时间】:2015-03-15 17:57:24
【问题描述】:

我在使用 knitr 和嵌入的 html 表格时遇到了一些问题。基本上发生的事情是当我在 html 中嵌入 xtable 输出时,html 标签被转义,导致输出不可读。 print.xtable 的输出似乎正确地产生了预期的输出(一个 html 表),但是当在嵌入 xtable 的文档上调用 knit 时,会产生转义字符。有人有解决办法吗?

提前致谢!

以下版本和代码示例:

  • RStudio 0.98.1103
  • R 3.13
  • 针织 1.9

    library("knitr")
    library("xtable")
    
    col1 <- c(1, 2, 3) 
    col2 <- c("a", "b", "c") 
    col3 <- c(TRUE, FALSE, TRUE) 
    df <- data.frame(col1, col2, col3)
    
    # display the dataframe 
    df
    
    # HTML is properly generated here
    tbl <- print(xtable(df),type="HTML",include.rownames=FALSE)
    
    testknitr <- "<html>
    <head>
    <title>Test Knitr from variable</title>
    </head>
    <body>
    <h1>Testing Knitr escaping </h1>
    <table>
    <tr>
    <td>
    <!--begin.rcode label=\"a table\" 
    tbl 
    end.rcode-->
    </td>
    </tr>
    </table>"
    
    # inspecting the file will show all < replaced with &lt; and > replaced with &gt;
    # and new lines replaced with \n, which does not render properly in a browser
    knit(text=testknitr, output="testknitr.html")}
    

【问题讨论】:

    标签: html r knitr


    【解决方案1】:

    您需要添加results="asis" 选项。

    尝试以下方法:

    testknitr <- "<html>
                  <head>
                      <title>Test Knitr from variable</title>
                  </head>
                  <body>
                      <h1>Testing Knitr escaping </h1>
                      <table>
                          <tr>
                             <td>
                   <!--begin.rcode label=\"a table\", results=\"asis\", echo=FALSE
                        print(xtable(df),
                              type=\"HTML\", 
                              include.rownames=FALSE) 
                   end.rcode-->
                             </td>
                         </tr>
                     </table>"
    
    knit(text=testknitr, output="testknitr.html")
    

    另外,在代码块中打印 xtable 的输出以避免不必要的换行符。

    【讨论】:

    • 谢谢你!这几乎得到了一切。周围还有一些错误的\n,但更近了!
    • 其实我还有一个错字,所以你的解决方案修正了它!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2015-10-11
    • 2023-04-01
    • 2011-08-06
    相关资源
    最近更新 更多