I would like to be able to create two versions of homework, tests, and lecture slides: with and without solutions. In general I can accomplish this by setting a variable to `TRUE`

or `FALSE`

, and then using it in the code chunk options: `{r, echo = SOLUTION, eval = SOLUTION}`

(or `{r, echo = SOLUTION}`

only if the solution can be contained in R comments and doesn't require evaluation). It becomes difficult however when I'd like to include math equations in the solution. Since to the best of my knowledge there is no option to toggle text sections in rmarkdown (though that would be a very welcome feature!), is there a workaround (ideally one that doesn't involve putting each solution in a separate file)? Thanks.

This works for me:

```
```{r show}
show_equations <- TRUE
```
```{r equationShown, include=show_equations, results='asis'}
cat("$$ 1 + 1 = 2 $$")
```
```{r hide}
show_equations <- FALSE
```
```{r equationHidden, include=show_equations, results='asis'}
cat("$$ 2 + 2 = 4 $$")
```
```

4 Likes

Oh wow, so simple! I'll just add a note for future readers to be sure to escape the \ in latex expressions:

`cat("$$\\sqrt{x}$$")`

Thank you!

1 Like

And another note: for knitting to HMTL, `<br>`

works for line breaks:

```
cat("$\\sqrt{x^2}=$<br>")
cat("$x$<br>")
```

1 Like