r knitr - 被转义的嵌入式HTML标签 - 如何关闭

时间:2015-03-15 17:57:24

标签: html r knitr

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

提前致谢!

以下版本和代码示例:

  • RStudio 0.98.1103
  • R 3.13
  • knitr 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")}
    

1 个答案:

答案 0 :(得分:2)

您需要添加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的输出以避免不必要的换行符。