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

2

8

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

Sig answered 26/9, 2017 at 15:55 Comment(3)
That is not possible with bookdown (at least for now).Eddy
@YihuiXie Is there any hope to have it work with something like r paste0("'''{example}\n") r paste0("If $a = ", a, "$ and $b = ", b, ", then $a + b = ", a + b, "$.\n") r paste0("'''") I can't find how to make it work with the ```.Sig
Unfortunately, no...Eddy
L
2

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

Laevorotatory answered 26/9, 2017 at 16:22 Comment(2)
Explicit LaTeX tags work fine for the PDF output but the html output doesn't contain the theorem nor the example (just the initial two lines of R code). Am I missing something?Sig
No, this method will only work for Latex. I forgot to consider whether this would work for html.Laevorotatory
B
0

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)
Borage answered 9/3, 2022 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.