Insert manually created markdown table in Sweave document

后端 未结 1 1456
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 22:41

I have a bunch of quite big tables in markdown that I created manually. I was using them in an Rmd document. Since I need more control with LaTeX and all, I am using a Rnw d

1条回答
  •  粉色の甜心
    2021-01-15 23:26

    It's doable:

    \documentclass{article}
    \usepackage{longtable}
    \usepackage{booktabs}
    \begin{document}
    
    <>=
    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}
    

    I wrapped the code in a small helper function markdown2tex. This makes the code quite slim when using it with several markdown tables.

    The idea is to simply copy the markdown table in the document and assign it as character string to an object (here: markdowntable). Passing markdowntable to markdown2tex includes the equivalent LaTeX table into the document. Don't forget to use the chunk options results = "asis" and message = FALSE (the latter in order to suppress messages from pandoc).

    The workhorse in markdown2tex is knitr::pandoc. With format = "latex", ext = "tex" it converts the input to a TEX fragment and returns the path to the TEX file (texfile). As pandoc needs a filename as input, the markdown string is written to a temporary file myfile. After printing the contents of texfile to the document, myfile and texfile are deleted.

    Of course, if the markdown tables are already saved in files, these steps can be simplified. But personally, I like the idea of having a markdown string in the RNW file. That way, it can be easily edited, the content is clear and it supports reproducibility.

    Note: You need to add \usepackage{longtable} and \usepackage{booktabs} to the preamble. The TEX code generated by pandoc requires these packages.

    The example above produces the following output:

    0 讨论(0)
提交回复
热议问题