How to use inline R code in a bookdown theorem or example environment

372 Views Asked by At

I use bookdown to generate documents in both html and PDF. How could I use results from inline R code in theorem and example environments?

Here is what I tried:

---
title: "Test"
output:
  bookdown::pdf_book:
    toc: false
html_document:
    toc: false
---

```{r}
a <- 2
b <- 3
```

If $a = `r a`$ and $b = `r b`$, then $a + b = `r a + b`$.

```{theorem}
If $a = `r a`$ and $b = `r b`$, then $a + b = `r a + b`$.
```

```{example}
If $a = `r a`$ and $b = `r b`$, then $a + b = `r a + b`$.
```

and I get Result

2

There are 2 best solutions below

0
On

To avoid this type of problems, I insert a blank environment (for numbering and reference only) and then write the content (you may want to end with a special character or ---).

```{example, myexample}
```
If $a = `r a`$ and $b = `r b`$, then $a + b = `r a + b`$.

---

See for instance \@ref(exm:myexample)
2
On

You could go with explicit Latex tags:

---
title: "Test"
output:
  bookdown::pdf_book:
    toc: false
html_document:
    toc: false
---

```{r}
a <- 2
b <- 3
```

\begin{theorem}

If $a = `r a`$ and $b = `r b`$, then $a + b = `r a + b`$.

\end{theorem}

\begin{example}

If $a = `r a`$ and $b = `r b`$, then $a + b = `r a + b`$.

\end{example}

enter image description here