# Resources

This page is intended to help newcomers get started compiling and editing LaTeX documents quickly!

### Templates & Example Documents

1. Software Installation: If you do not yet have LaTeX installed, start here!
2. Editing LaTeX Documents: A quick overview of the basics to get you started.
3. Integrate R code using knitr: Type R code directly into a LaTeX document, and let the knitr package run the code and format the output for you! Here is how to configure TeXstudio to complie *.Rnw documents (recommended), or use RStudio.

## 0. Pronunciation of TeX and LaTeX

Simply pronounce the X like a K: TeX is pronounced like tech in technology; LaTeX is pronounced as LAY-tek or LAH-tek.

## 1. Software Installation

Your instructors or colleagues may have great advice for which software to use, so ask! Unless you already have a favorite all-purpose code editor, I highly recommend something user friendly and LaTeX specific.

To get started (especially if you don't have your own computer) you can avoid installing software by using a cloud-ased LaTeX editor and storage space like OverLeaf.com (formerly WriteLaTeX.com) or ShareLaTeX.com, which both offer free accounts. Many people use such services as a secondary editing enviroment, e.g., to collaborate on shared documents.

If you (like most people) prefer locally installed software, I recommend TeXStudio because it's free and it runs on Windows, Mac, and Linux operating systems -- that is, you and your collaborators (be they coauthors on a paper, lab members, or students in a class) can all use the same software!

To generate TeX/LaTeX documents, you'll need to install some software:

1. A TeX/LaTeX compiler like MiKTeX (windows) or TeX Live (multiple platforms);
3. An editor like TeXStudio that "speaks LaTeX" and can orchestrate all of the other software so you don't have to think about it.
Whew! Fortunately, you can easily install everything at once! Also, if you're working on a document with a big bibliography you might also add a bibliography manager that knows how to work with BibTeX files (e.g. JabRef or BibDesk).

To install TeXStudio and the other necessary software:

### Mac OS Installation

• MacTeX -- Have lots of extra room on your hard drive? Whether you install TeXStudio or the popular Mac OS editor TexShop, do it via MacTeX. However...

I recommend you save space and download time and instead install BasicTeX (the light version of MacTeX that can automatically download missing packages later; only 110 megabytes instead of 2 gigabytes), Ghostscript (look for the Ghostscript.pkg link here), the TeXstudio or TeXShop editor, and maybe LaTeXiT.

### Linux Installation

• You got this! Right? Of course you do! Moving on...

## 2. Editing LaTeX Documents

Here is an example article and some related files to get you started. If you have LaTeX software installed on your computer, open up a new document and save it as "examples.tex" in a new project directory, so you can compile the document and changes below to see how things look.

A few tips for new users:

1. Pay attention to spacing and indentation. Keep things clean!
2. Explore your editor menus -- a good LaTeX editor has a lot of handy formatting commands built in. Click these as needed -- it's a great way to learn and remember common formatting commands, math symbols, and formatting environments!
3. Ask for help - If they use it, your friends and colleagues will be thrilled to see you learning LaTeX, and you'll work better together when your LaTeX habits are in sync.
4. Use LaTeX regularly -- A great way to learn it well. You can also use LaTeX to write math expressions in other applications, like WordPress blogs, Microsoft Office applications (via LaTeXit) on Macs (OS X only), etc.

Students: study by rewriting your course notes in LaTeX (preferred), or by typing notes in LaTeX in class (more time efficient, but perhaps less effective for learning).
5. In larger documents, ALWAYS use commands like \ref{} to refer to labeled figure numbers, equation numbers, etc. Never type in the figure or table number directly! LaTeX manages those reference numbers for you, and updates them when new figures, equations, etc. get added to the document.

### Anatomy of a LaTeX file

LaTeX files include a header followed by the main body of the document. The header includes instructions to load additional packages, set default formatting parameters, etc. The body contains a mix of document text and LaTeX commands for formatting that text. Here's an example:

\documentclass{article} % Specify article, report, etc. to set format defaults
% All text after a "%" until the end of the line are comments.

% Packages: add-on routines for specific formatting needs. For example,
\usepackage{graphicx}                 % if we want to include figures.
\usepackage[margin=0.5in]{geometry}   % an easy way to setup more compact margins

% This is the end of the HEADER -- where we set document-wide format defaults.

\begin{document}        % First, let's set up the title page.
\title{\LaTeX{} Example} % \LaTeX{} returns fancy text.
\author{John Q. Public}
\maketitle               % Use the above information and format the first page.

% \begin{abstract} ... \end{abstract} % If you're writing a paper

\section{Introduction}
This text appears as the first sentence in my document.
$$\label{eq:ex1} % label equation using the eq:NAME and fig:NAME convention \dot{x} = f(x)$$
The nice thing about using labels for equations, figures, citations, etc. is
that \LaTeX{} will take care of all the numbering for you!  If I moved
equation \ref{eq:ex1}, all my references will still be numbered correctly.
\end{document}


Next, let's focus on editing the body, e.g. as if we wanted to update a draft manuscript, or create a set of typed course notes using an existing template file. We'll skip discussion of how to customize your document formatting by modifying the header: using packages, style sheets, bibliograpy tools, etc. Look online for those formatting examples.

### LaTeX Commands

Have another look at the document content in the above example (comments omitted):
\begin{document}
% ...
\section{Introduction}
This text appears as the first sentence in my document.
$$\label{eq:ex1} \dot{x} = f(x)$$
The nice thing about using labels for equations, figures, citations, etc. is
that \LaTeX{} will take care of all the numbering for you!  If I moved
equation \ref{eq:ex1}, all my references will still be numbered correctly.
\end{document}


A basic category of LaTeX elements are commands, which take the form

\name[modifier]{input}
There may be multiple {} and [] options, or none at all. A good LaTeX editor, like TeXStudio, will help you remember these by including common commands in the drop-down menus. Text in braces {like this} is often referred to as a block. Many commands act on the next block (the next character, by default), but it is best to use braces and not rely on defaults: \textbf{Which part is bold? All!} might (or might not) yield the same results as \textbf Which part is bold?.

### Equations

There is no better reference than the American Mathematical Society's (AMS's) Short Math Guide for LaTeX (PDF). I highly recommend saving a copy where you can easily find it (consider bookmarking that saved copy in your web browser!). Skim it, look for what you want, then see the code. Make sure your document header has \usepackage{amssymb, amsmath} as these packages are required for some of the commands and environments covered in the guide.

### Formatting Text

The most common commands you'll use deal with formatting text. A good editor, like TeXStudio, will have menu shortcuts (similar to formatting in other text editors, like MS Word) that will insert the right LaTeX commands for you. Here are some common ones:
\begin{document}
% ...
\section{Introduction}\label{Intro}
This text appears as the first sentence in my document.
These are: \textbf{bold}, \textit{italicized}, \emph{also italicized}, \texttt{courier new / typewriter}.
$$\label{eq:ex1} \dot{x} = f(x)$$
The nice thing about using labels for equations, figures, citations, etc. is
that \LaTeX{} will take care of all the numbering for you!  If I moved equation \ref{eq:ex1}
out of section \ref{Intro}, all references will still be numbered correctly.
\end{document}


### References in LaTeX

One of the key strengths (and big differences) of LaTeX over editors like MS Word are the wonderful referencing capabilities. References to section numbers, figure numbers, appendices, equations, etc. can all be done by marking them with \label{name}, where the name often includes a prefix to indicate whether it's a figure, equation, etc. References in the text can then be written in terms of these labels, and LaTeX will fill in the numbers for you! Including those numbers in the text is done with \ref{name} or more specialized versions that allow specific formatting, like \eqref{name}. We'll discuss bibliographic citations in the relevant section below.

\begin{document}
% ...
\section{Introduction}\label{Intro}
Here we have a new equation
$$\label{eq:new} a=b+c$$
which appears before our original equation
$$\label{eq:ex1} \dot{x} = f(x)$$
All locations where I had referred to equation \ref{eq:ex1} in the
text are now automatically updated to point to the right equations!
The same holds true for numbered citations when you add a reference
\end{document}


### Bibliographies

There are two ways to include this information: by writing it all into the end of the main document, or by including it in a separate BibTeX file and using the cite or natbib package (use the latter, as it is an extension of the former) to format things for you. Most prefer the BibTeX approach, but we'll briefly look at modifying documents of either type.

The first approach embeds the citation information into the end of the document directly, and looks something like:
... and so the last citation in this document is \cite{lamport94}.
In practice, I tend to specify whether I want an in-line text citation,
like \citet{lamport94} or a parenthetical one \citep{lamport94}.

%% Here's our bibliography information.
\begin{thebibliography}{9}

\bibitem{lamport94}
Leslie Lamport,
\emph{\LaTeX: A Document Preparation System}.
2nd Edition,
1994.
\end{thebibliography}

\end{document}


To add a new reference, just copy the current format (see the above link if you need more help).

The more popular approach keeps all this in an external file and uses the package natbib, which allows more flexible formatting. Most journal websites and citation management software allows for exporting things in this (BibTeX) format! In this case, your document ends with just one line, pointing to the BibTex file that contains your citation info:

\bibliography{./myBibTeXfile} % which is actually named myBibTeXfile.bib
\end{document}

Entries in myBibTeXfile.bib look like
@article{Hurtado2012,
title = {{Within-host dynamics of mycoplasma infections: Conjunctivitis in wild passerine birds}},
year = {2012},
journal = {Journal of Theoretical Biology},
volume = {306},
number = {0},
pages = {73 - 92},
doi = {http://dx.doi.org/10.1016/j.jtbi.2012.04.018},
url = {http://www.sciencedirect.com/science/article/pii/S0022519312001993}
}

@book{Murdoch2003,
title = {{Consumer-Resource Dynamics}},
author = {Murdoch, William W. and Briggs, Cheryl J. and Nisbet, Roger M.},
year = {2003},
publisher = {Princeton University Press},
series = {Monographs in population biology; 36},
isbn = {13: 978-0-691-00657-4},
url = {http://press.princeton.edu/titles/7569.html}
}

title = {{Infectious disease ecology: Immune-pathogen dynamics, and how trophic
interactions drive prey-predator-disease dynamics}},
school = {Cornell University},
year = {2012},
type = {PhD Thesis},
month = {January}
}

To update, or add references, it's best to use a BibTeX manager like JabRef (windows) or BibDesk (OS X), however you can also easily edit the *.bib file with your regular text editor once you know what you're doing.

### Templates

Most journals that publish mathematical content provide LaTeX template files. See their author instructions. If you have a target journal in mind, consider downloading their template sooner rather than later -- it's a great way to see how your paper will look when formatted for the journal (e.g., to check font sizes in figures, equation alignment, etc.) and saves you the work of reformatting.

See the workshop files and templates at the top of this page for some basic templates for various document types.

## 3. Integrating R code and output into LaTeX Documents

There are two approaches here depending on whether you want to have a document that is mostly LaTeX with a little R code and output (an Sweave of knitr file, with extension *.Rnw), or a document that is mostly R code with a little plain text and LaTeX here and there (R Markdown, with extension *.Rmd).

R Studio can compile both document types (assuming it is configured to know where you LaTeX installation is located), and TeXstudio can configured to easily compile *.Rnw files.

### 3.1 R code chunks in LaTeX documents (aka knitr documents)

These knitr documents (which are similar to Sweave documents) are basically LaTeX documents with file extension *.Rnw, and include "code chunks" that are run at compile time (in R) and replaced by nicely formatted code and/or R output. Setup TeXstudio to compile knitr (*.Rnw) documents by following these instructions.

There is an example document in homework-template.zip, and you can read more about using knitr at

### Adding R code to an existing LaTeX Document:

Here is a minimal set of instructions for taking an existing LaTeX document and turning it into a knitr document that includes a chunk of R code. This would add a nicely formatted version of the code and the corresponding figure, to your compiled document (i.e. the PDF or DVI).
1. Save a copy of your LaTeX document (e.g., myreport.tex) with file extension *.Rnw (e.g., myreport.Rnw).
2. Right after the \begin{document} add the following knitr code block (this just modifies default formatting):
<<setup, include=FALSE>>=
# smaller font size for chunks
knitr::opts_chunk\$set(size = 'footnotesize', concordance=TRUE)
options(scipen=1, digits=4)
@

Here's how these code blocks work: everything between the line <<...>>= and the line with just a '@' on it is going to be interpreted by the knitr package in R as R code. Code blocks each need a unique name (the first argument, 'setup', in this example) and can be modified in various ways by additional arguments (e.g. include=FALSE tells the knitr package to run this code, but not show this code in the final document). Here the details of the R code are just arguments to setup formatting, so read up on knitr to make sense of those.
3. Next, we can create similar code blocks elsewhere in the document and fill them with R code, and both the code and results will be automatically embedded in the document. For example, adding the following code block to your document would result in a nicely formatted version of the code and R output, followed by a plot a simple sin curve:
<<sinplot, fig.height=3, fig.width=6>>=
# This is a regular old R comment
1+1
curve(sin(x),-10,10)
@

4. Again, for more, see the links above and make use of search engines like google to dig up additional examples and formatting fixes.

### 3.2 LaTeX in R Markdown Documents

In short, if you know R markdown, you can easily include LaTeX commands (e.g. equation environments) and these will compile as desired. Just make sure Rstudio knows where your LaTeX installation is at, and/or that your path includes directories for your LaTeX software (e.g. MikTeX). See this RStudio page for more on R Markdown: rmarkdown.rstudio.com/.

To get started with R Markdown documents, open up RStudio and go to File > New File > R Markdown... This will create a template document that includes an example code block, text formatting, and (importantly!) a link to the R Studio webpage which has more information on R Markdown. See also their Cheat Sheets for R Markdown (I prefer the old one to the new one).