【问题标题】:How to use R to convert character from markdown to LaTeX如何使用 R 将字符从 Markdown 转换为 LaTeX
【发布时间】:2019-12-01 08:47:20
【问题描述】:

我有一个变量,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】:

    只需将您的字符串写入临时文件,然后进行转换。我建议使用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))
    

    【讨论】:

    • 是的,我认为这是我必须做的。有没有推荐的地方用 R 存储临时文件?还是当前工作目录够用?
    • 使用tempfile()。 cwd 可能会踩到重要的东西。
    • 哦,呵呵。我现在看到了。谢谢。
    • 所以看起来rmarkdown::render 在 72 个字符处换行(或类似的字符)。因此,如果不希望这样做,您可以使用 y &lt;- readLines(outfile)stringr::str_c(y, collapse = " ")
    【解决方案2】:

    使用 commonmark 包有一个更清洁和更简单的解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      • 2020-12-21
      • 1970-01-01
      • 2017-05-11
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多