在 Sweave 文档中插入手动创建的 markdown table

Insert manually created markdown table in Sweave document

我在手动创建的 markdown 中有一堆相当大的 tables。我在 Rmd 文档中使用它们。由于我需要对 LaTeX 和所有内容进行更多控制,因此我使用的是 Rnw 文档。如何将降价 table 放入 Sweave 文件中?

下面是一个最小的例子(不起作用):

\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}

% my markdown table

col1 | col2 | col3
------|:---:|:---:
row1 | cell1 | cell2 
row2 | cell3 | cell4 
row3 | cell5 | cell6 


\end{document}

我试图转换文档中的 table,只是为了将 table 粘贴到 Sweave 文档中的 markdown 中,并使其在 LaTeX 中呈现。我的尝试产生错误,但我更接近:

\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}

<<texifytable, echo=FALSE, results=tex>>=
mytab = sprintf("col1 | col2 | col3
------|:---:|:---:
row1 | cell1 | cell2 
row2 | cell3 | cell4 
row3 | cell5 | cell6")
system2("pandoc", args = c("-f markdown","-t latex"),
        stdout = TRUE, input = mytab)
@

\end{document}

可行:

\documentclass{article}
\usepackage{longtable}
\usepackage{booktabs}
\begin{document}

<<echo = FALSE, results = "asis", message = FALSE>>=
library(knitr)

markdown2tex <- function(markdownstring) {
  writeLines(text = markdownstring,
             con = myfile <- tempfile())
  texfile <- pandoc(input = myfile, format = "latex", ext = "tex")
  cat(readLines(texfile), sep = "\n")
  unlink(c(myfile, texfile))
}

markdowntable <- "
col1 | col2 | col3
-----|:----:|:----:
row1 | cell1 | cell2
row2 | cell3 | cell4
row3 | cell5 | cell6
"

markdown2tex(markdowntable)
@
\end{document}

我将代码包装在一个小的辅助函数中 markdown2tex。这使得代码在与多个 markdown tables.

一起使用时非常苗条

想法是简单地复制文档中的 markdown table,并将其作为字符串分配给一个对象(这里:markdowntable)。将 markdowntable 传递给 markdown2tex 会将等效的 LaTeX table 包含到文档中。不要忘记使用块选项 results = "asis"message = FALSE(后者是为了抑制来自 pandoc 的消息)。

markdown2tex 中的主力是 knitr::pandoc。使用 format = "latex", ext = "tex" 它将 input 转换为 TEX 片段和 returns TEX 文件的路径 (texfile)。由于 pandoc 需要一个文件名作为输入,markdown 字符串被写入一个临时文件 myfile。将texfile的内容打印到文档后,myfiletexfile被删除。

当然,如果markdown table已经保存在文件中,这些步骤就可以简化。但就我个人而言,我喜欢在 RNW 文件中使用降价字符串 的想法。这样编辑方便,内容清晰,支持复现。

注意:您需要在序言中添加\usepackage{longtable}\usepackage{booktabs}pandoc 生成的 TEX 代码需要这些包。

以上示例产生以下输出: