# Including source code in LaTeX documents

Needed to include some R script in a document. Pasting straight in causes problems. Turns out the \listings package works well. Settings need to be tweaked a bit but otherwise easy to use. Can take other languages than R as input too.

% %Preamble
\documentclass{article}

\usepackage[usenames,dvipsnames]{color} % Important for r script boxes
\usepackage{listings} % Important for r script boxes

\begin{document}

\lstset{
language=R,                     % the language of the code
numbers=left,                   % where to put the line-numbers
backgroundcolor=\color{white},  % choose the background color
frame=single,                   % frame around code
rulecolor=\color{black},        % if not set, the frame-color may be changed on line-breaks within not-black text
tabsize=1,                      % sets default tabsize
breaklines=true,                % sets automatic line breaking
breakatwhitespace=false,        % sets if automatic breaks should only happen at whitespace
keywordstyle=\color{Blue},      % keyword style
stringstyle=\color{ForestGreen} % string literal style
}

\section{Some R code}
\begin{lstlisting}
## Some example R code
Data <- data.frame(
X = sample(1:10),
Y = sample(c("something", "somethingElse"), 10, replace = TRUE)
)
}
\end{document}
\end{lstlisting}

\end{document}


Output: