# How can I nest a code chunk within an enumerate environment when using R Markdown?

When I attempt to do this using this code:

---
title: "Title"
author: "Me"
date: "31 October 2014"
output:
pdf_document:
includes:
---

\begin{enumerate}[label=\textbf{\arabic*})]
\item
\begin{enumerate}
\item
{r}
print("test")


\end{enumerate}
\end{enumerate}


includes.sty just contains:

\usepackage{enumitem}


R studio does not recognise the chunk as a valid code block (no syntax highlighting), and when compiling I get the error:

! You can't use macro parameter character #' in horizontal mode.
l.199         #


Is there any other way to do this?

• Welcome to TeX.SX! Please help us to help you and add a minimal working example (MWE) that illustrates your problem. It will be much easier for us to reproduce your situation and find out what the issue is when we see compilable code, starting with \documentclass{...} and ending with \end{document}. – user31729 Nov 1 '14 at 12:15
• Okay, I've added the full file. Adding \documentclass{...} isn't necessary in this instance (as I'm guessing that it is automatically included when the source is compiled). – JackWoot Nov 1 '14 at 12:25

There are basically two things causing errors in your sample code:

1. By default, knitr prefixes R output with ##, which can't be present in your TeX file. You have to substitute something else for it.
2. Code chunks can't be indented, so you'll have to excuse your OCD self and flush the chunk to the left of your source code.

So this alone makes improves your code:

\begin{enumerate}
\item
\begin{enumerate}
\item
{r, comment="", results="asis"}
print("test")

\end{enumerate}
\end{enumerate}


Your PDF should look like this:

Notice how the final product is a monstrous TeX-knitr hybrid. It interpreted the R markdown, but printed everything in LaTeX. Notice how the triple quotes were converted to double quotes + single quote. Removing results="asis" just makes things a bit worse, because then the answer also gets those quotes.

I've found an awesome answer on Stackoverflow that shows a nice trick to get proper formatting. You just have to rename your environment:

---
output: pdf_document
- \newcommand{\benum}{\begin{enumerate}}
- \newcommand{\eenum}{\end{enumerate}}
---
\benum
\item
\benum
\item
{r, results="asis"}
print("test")

\eenum
\eenum


Result:

Removing results="asis" should give better (i.e., monospaced) formatting for the R output, but instead it just yields the following error on my machine:

LaTeX Error: \begin{enumerate} on input line 664 ended by \end{document}.

## TL;DR

1. Renew your commands on the preamble (e.g.: \newcommand{\benum}{\begin{enumerate}})
3. Use results="asis"