[Tex/LaTex] How to insert equation numbers with lstlisting

cross-referencingequationslistings

I am trying to use the lstlisting environment to insert R code into my LaTeX document. What I cannot figure out is how to get LaTeX to number these equations so that I can refer back to them later in the text. I want to do something like this:

\begin{lstlisting}[language=R]
lm.model <- lm(Total.Score ~ Game.Num, data = sid1133)
\end{lstlisting}\label{eq:lm.model}

To be clear — I know I can do this:

\begin{lstlisting}[language=R, caption={Standard Linear Regression Model Equation}, label=foobar]
lm.model <- lm(Total.Score ~ Game.Num, data = sid1133)
\end{lstlisting}

However, I want to put the equation number to the right of the equation — not in a separate header at top, and I want to be able to refer to it later in the text.

Best Answer

To be able to create an R-listing (or actually any listing) inside \begin{equation} ... \end{equation}, you'll need to use \lstinline instead of \begin{lstlisting} ... \end{lstlisting}. To start and end the code snippet, you can use any character which is not used within the code. A popular choice is e.g. | or $:

\lstinline[language=R]|lm.model <- lm(Total.Score ~ Game.Num, data = sid1133)|

but again, it doesn't matter as long as that character does not appear in your code snippet.

To be able to place this \lstinline within an equation, you have to "escape" math mode first, so you are in the "normal" text mode. This is done with \text{any content which is not math}. So together, this is

\documentclass{article}
\usepackage{listings}
\usepackage{amsmath}
\begin{document}
As described in \eqref{eq:lm.eq:lm.model}, this is very important.
\begin{equation} \label{eq:lm.eq:lm.model}
    \text{\lstinline[language=R]|lm.model <- lm(Total.Score ~ Game.Num, data = sid1133)|}
\end{equation}
\end{document}

enter image description here

Related Question