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

问题描述 投票:1回答:1

我有一个变量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几乎在那儿,但是需要输入和输出文件。

r text latex r-markdown knitr
1个回答
3
投票

只需将您的字符串写入临时文件,然后进行转换。我建议使用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))
© www.soinside.com 2019 - 2024. All rights reserved.