My little demo code borrows from here is given as follows (test.rmd):
---
documentclass: article
output:
pdf_document:
number_sections: yes
keep_tex: no
geometry: "left = 2.5cm, right = 2cm, top = 2cm, bottom = 2cm"
fontsize: 11pt
header-includes:
- \newtheorem{ex}{Exercise}
- \usepackage[nosolutionfiles]{answers}
- \Newassociation{sol}{Solution}{ans}
- \renewcommand{\Solutionlabel}[1]{\textbf{Answer.}}
---
knitr::opts_chunk$set(
error = TRUE,
message = FALSE,
warning = FALSE
)
\section{Problems}
\begin{ex}
First exercise
\begin{sol}
First solution.
\end{sol}
\end{ex}
It works well. However, when I inset some R code chunks in it like
\begin{ex}
Second exercise
\begin{sol}
Second solution.
```{r}
1+2
```
\end{sol}
\end{ex}
it makes an error showing
! You can't use `macro parameter character #' in horizontal mode.
Weirdly, we can use the R code chunks outside the environments \begin{ex}...\end{ex} and \begin{sol}...\end{sol}!
How to fix this?
