haff
haff

Reputation: 956

How to use R to convert character from markdown to LaTeX

I have a variable, x, which is a character formatted using markdown:

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

I want to convert it to Tex so that it looks like this

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

Is there an R function that achieves this? The backslashes themselves might need to be escaped, but you get the idea. I'm certain this exists as it's easy to convert an from .Rmd to a .pdf, but I'd prefer not to create and write an intermediate .tex file since this will need to be repeated a lot.

I've dug around the vignettes, documentation, and source code for both knitr and RMarkdown but I can't find what I'm looking for.

EDIT

So I found knitr::pandoc which is almost there but requires input and output files.

Upvotes: 3

Views: 614

Answers (2)

Stefan F
Stefan F

Reputation: 2753

There is a cleaner and simpler solution for this using the commonmark package:

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

Upvotes: 4

user2554330
user2554330

Reputation: 44937

Just write your string to a temp file, and convert that. I recommend using rmarkdown::render instead of knitr::pandoc; they both call pandoc, but the former sets all the options for you:

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)

This produces the following output:

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

For neatness, you could remove the two temp files at the end:

unlink(c(infile, outfile))

Upvotes: 4

Related Questions