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

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


  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
  commentstyle=\color{Green},     % comment style
  stringstyle=\color{ForestGreen} % string literal style

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


Screenshot from 2015-01-18 00:48:38


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s