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

eipi10
  • 91,525
  • 24
  • 209
  • 285
QuantIbex
  • 2,324
  • 1
  • 15
  • 18
  • 1
    That is not possible with bookdown (at least for now). – Yihui Xie Sep 26 '17 at 18:32
  • @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 ```. – QuantIbex Sep 26 '17 at 19:23
  • Unfortunately, no... – Yihui Xie Sep 27 '17 at 02:09

2 Answers2

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

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • 1
    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? – QuantIbex Sep 26 '17 at 16:42
  • No, this method will only work for Latex. I forgot to consider whether this would work for html. – eipi10 Sep 26 '17 at 16:44
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)