Thanks Achim for your quick and detailed reply — and apologies for including an image of the code. I tried to use the “four backticks” trick (I even attempted something similar at some point) but couldn’t get it to work.
Both of your proposed solutions work fine; the second one, based on "mytemplate.md", is clearly preferable.
There’s only one remaining issue: if I include a graph in the R code, the following is added to the latex file.
\pandocbounded{\includegraphics[keepaspectratio]{media/supplements1/exercise1/ex1-unnamed-chunk-3-1.png}}
However, pdflatex compilation fails because it cannot find the PNG file (I wasn’t able to locate where it gets saved — maybe a temporary folder?). Do you have any idea how to fix this?
By the way, my ultimate goal is to produce a PDF file with all the exercises so I can quickly scan them when preparing exams. With the code I wrote and your suggestions, I’ve almost reached that goal.
Thanks a lot for the wonderful package!