如何使用 R 将字符从 markdown 转换为 LaTeX

How to use R to convert character from markdown to LaTeX

我有一个变量,x,它是一个使用 markdown 格式化的字符:

x <- "Here is some _great_ text in a **variable** and some blank spaces ____."

我想把它转换成 Tex,这样它看起来像这样

y <- some_library::md2tex(x)
y
[1] "Here is some \textit{great} text in a \textbf{variable} and some blank spaces \_\_\_\_."

是否有实现此功能的 R 函数?反斜杠本身可能需要转义,但你明白了。我确定这是存在的,因为将 .Rmd 转换为 .pdf 很容易,但我不想创建和编写中间 .tex 文件,因为这需要重复很多次.

我已经搜索了 knitrRMarkdown 的插图、文档和源代码,但找不到我要找的东西。

编辑

所以我找到了knitr::pandoc,它几乎就在那里,但需要输入和输出文件。

只需将您的字符串写入临时文件,然后进行转换。我建议使用 rmarkdown::render 而不是 knitr::pandoc;他们都调用 pandoc,但前者为您设置了所有选项:

x <- "Here is some _great_ text in a **variable** and some blank spaces ____."
infile <- tempfile(fileext=".md")
writeLines(x, infile)
outfile <- rmarkdown::render(infile, rmarkdown::latex_fragment(), quiet = TRUE)
readLines(outfile)

这会产生以下输出:

[1] "Here is some \emph{great} text in a \textbf{variable} and some blank"
[2] "spaces \_\_\_\_."  

为了整洁起见,您可以删除最后的两个临时文件:

unlink(c(infile, outfile))

使用 commonmark 包有一个更干净、更简单的解决方案:

commonmark::markdown_latex("Here is some _great_ text in a **variable** and some blank spaces ____.")