0

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?

  • 2
    Please always show the full generated LaTeX code in this case. Not everyone here uses Rmarkdown but many of us can debug LaTeX code and explan what is wrong. – daleif Nov 07 '23 at 15:53

1 Answers1

4

The output of the sum is ## [1] 3 and including it in a LaTeX environment it passed to the LateX engine as markdown text:

```r
1+2
```
## [1] 3

The result is the same fatal error that type "#" unescaped in LaTeX:

\documentclass{article}
\begin{document}
hello #  
\end{document}

One solution is specify not only what is R code, but also what is LaTeX within the markdown, but excluding the R chunk inside, that is:

```{=tex}
\begin{ex}
Second exercise
\begin{sol}
Second solution.
```
1+2
\end{sol}
\end{ex}

Then the R chunk is processed before to pass it to the LaTeX export:

mwe

Fran
  • 80,769
  • 1
    +1 perfect explanation – MS-SPO Nov 07 '23 at 17:39
  • It works! Great! I just wandering whether we can fix the problem via the setting in preamble or yaml part of the rmd file @Fran As we known, if there are too many code chunks in the file, your solution may be somewhat inconvenient ... – John Stone Nov 08 '23 at 02:01
  • 1
    @JohnStone It's just a matter of being aware of the order in which each language are processed, to avoid nesting in the wrong order. You can combine **foo \emph{bar} baz** to produce \textbf{foo \emph{bar} baz} without mark anything as LaTeX code, but the opposite will not work (i.e., \textbf{foo *bar* baz}) because the algorithm must assume that here "*bar*" is LaTeX too, and the same apply with the R chunks, only that with one more layer of possible wrong nesting. – Fran Nov 08 '23 at 14:28