Rui Vieira
Rui Vieira

Reputation: 5328

How to prevent string escaping in a LaTeX block with inline R code in RMarkdown?

I'm trying to format a matrix to be displayed as LaTeX in a RMarkdown document by using something along the lines of:

Having a function which translates an R matrix into a LaTeX string:

bmatrix = function(x, digits=NULL, ...) {
 library(xtable)
 default_args = list(include.colnames=FALSE, only.contents=TRUE,
                  include.rownames=FALSE, hline.after=NULL,
                  comment=FALSE,
                  print.results=FALSE)
 passed_args = list(...)
 calling_args = c(list(x=xtable(x, digits=digits)),
               c(passed_args,
                 default_args[setdiff(names(default_args),
                 names(passed_args))]))
 cat("\\begin{bmatrix}\n",
  do.call(print.xtable, calling_args),
  "\\end{bmatrix}\n")
}

such that:

bmatrix(diag(2))

gives

\begin{bmatrix}
 1.00 & 0.00 \\ 
 0.00 & 1.00 \\ 
\end{bmatrix}

The problem is that when I inline this in a LaTeX block:

$$
M = `r bmatrix(diag(2))`
$$

The matrix part is empty (I only get "M=").

I suspect this has something to do with RMarkdown and/or pandoc escaping the HTML entities in the LaTeX string.

Is there any way around it?

I've also tried

$$
M = `r I(bmatrix(diag(2)))`
$$

but to no avail.

Upvotes: 1

Views: 845

Answers (1)

Weihuang Wong
Weihuang Wong

Reputation: 13108

Try

$$
M = 
```{r, results='asis'} 
bmatrix(diag(2))
```
$$

From R Code Chunks:

the use of the results='asis' chunk option... is required to ensure that the raw table output isn’t processed furthur by knitr.


MWE

---
title: "Untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

```{r}
bmatrix = function(x, digits=NULL, ...) {
 library(xtable)
 default_args = list(include.colnames=FALSE, only.contents=TRUE,
                  include.rownames=FALSE, hline.after=NULL,
                  comment=FALSE,
                  print.results=FALSE)
 passed_args = list(...)
 calling_args = c(list(x=xtable(x, digits=digits)),
               c(passed_args,
                 default_args[setdiff(names(default_args),
                 names(passed_args))]))
 cat("\\begin{bmatrix}\n",
  do.call(print.xtable, calling_args),
  "\\end{bmatrix}\n")
}
```

# Foo

$$
M = 
```{r, results='asis'} 
bmatrix(diag(2))
```
$$

produces

enter image description here

Upvotes: 2

Related Questions