1
votes

In R, I have character objects that contain LaTeX macro definitions. The challenge is to use these objects in R Markdown documents, so that the macro definitions are rendered correctly when the .Rmd files are converted to LaTeX (and then to PDF). It is a challenge because Pandoc (v2.9.1 and 2.9.2) fails to render some macro-generating code correctly, even when that code is valid LaTeX.

Here is a minimal example. First, consider this Rmd file:

---
title: "Rendering LaTeX Macros from R Objects"
output: 
  pdf_document:
    keep_md: true
    keep_tex: true
---

```{r}
withoutBraces <- "\\newcommand\\withoutBraces{This is a sentence.}"
withBraces    <- "\\newcommand{withBraces}{This is a sentence.}"
```

```{r, results = "asis"}
writeLines(withoutBraces)
writeLines(withBraces)
```

Knitting this .Rmd file from RStudio produces a .tex file that includes the following output:

\newcommand\withoutBraces{This is a sentence.}

but

\textbackslash newcommand\{withBraces\}\{This is a sentence.\}

In other words, the \withoutBraces command is rendered correctly in the .tex document, but the \withBraces command is not. Inspection reveals that the rmarkdown::render() part of the knitting process is fine, in the sense that it produces an unproblematic .md file. The problem lies with pandoc: when it converts the .md file to a .tex file, the \withBraces command doesn't render correctly.

If I were writing .md files instead of .Rmd files, I could use "generic raw attributes" in my code chunks to get the \withoutBraces macro definition to render correctly, as in this example from @mb21. But I don't see a way to do that when working with R Markdown files. Is there anything that I can do to get the \withoutBraces definition to render correctly when I am knitting an .Rmd file to LaTeX and PDF?

1

1 Answers

0
votes

The problem lay with a LaTeX formatting error on my part, not in any problem with pandoc. I had written

withBraces    <- "\\newcommand{withBraces}{This is a sentence.}"

when I should have written

withBraces    <- "\\newcommand{\\withBraces}{This is a sentence.}"

When I use the second string instead of the first, there is no problem with the conversion to LaTeX.