How should I code solutions to exercises in the book I am writing using the bookdown
package?
I'm currently writing a book using the bookdown
R package. The book is broken down into chapters, and each chapter has exercises in a markdown numbered list. I would like to be able to put the solutions directly under the exercises without messing up the numbering of the problems, and in such a way that I can toggle whether the solutions are printed. I would also like to be able to pull out selected solutions (or all solutions) to form a solutions manual that gets printed out as an appendix. So far, I have two methods, which I call the "hidden R chunk method" and the "YAML method" but neither seems ideal, and can only be used to create a solutions manual.
1. Exercise one compute 1+1.
```{r, echo = FALSE, eval = FALSE}
#Solution
1+1
#BeginText The solution is `r 1 + 1`.
#EndText
```
1. Exercise two: compute 2^2.
```{r, echo = FALSE, eval = FALSE}
#Solution
2*2
#BeginText The solution is $2^2 = $`r 2*2`.
#EndText
```
I then wrote a script that pulls out anything with the #Solution comment, and breaks the #BeginText and #EndText out like this:
###Problem 1.
```{r }
1+1
```
The solution is `r 1 + 1`.
###Problem 2.
```{r }
2*2
```
The solution is $2^2 = $`r 2*2`.
and saves that in a new .Rmd file with appropriate headers.
The second solution involves YAML in between the exercises.
1. Exercise one compute 1+1.
---
solution: |
```{r}
1+1
```
The solution is `r 1 + 1`.
---
My co-author had hoped that he could pull out the YAML using an existing parser, but ended up having to write a script just like the hidden R chunk method. I'm not sure how bad of an idea it is to use YAML like this. Both solutions require that each exercise have at least a solution stub in order for the numbering to be the same.
I would like the solutions of the exercises to be connected to the exercise in some way, so that if we re-arrange the exercises or add new exercises, nothing breaks. I would also like to be able to pull out some or all of the solutions into separate markdown files that we can use to create a solutions manual.
How should we do this?