\documentclass[author-year]{elsarticle} %review=doublespace preprint=single 5p=2 column
\usepackage{amsmath, amsfonts, amssymb}  % extended mathematics
\usepackage{ifxetex}
\ifxetex
  \usepackage{fontspec,xltxtra,xunicode}
  \defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
  \setmainfont[Mapping=tex-text]{TeX Gyre Pagella}
  \setsansfont[Mapping=tex-text]{DejaVu Sans}
  \setmonofont{Bitstream Vera Sans Mono}
\else
  \usepackage[mathletters]{ucs}
  \usepackage[utf8x]{inputenc}
\fi

% My package additions
\usepackage[hyphens]{url}
\usepackage{lineno} % add 
%\linenumbers % turns line numbering on 
\bibliographystyle{elsarticle-harv}
\biboptions{sort&compress} % For natbib
\usepackage{graphicx}
\usepackage{booktabs} % book-quality tables

%% Redefines the elsarticle footer
\makeatletter
\def\ps@pprintTitle{%
 \let\@oddhead\@empty
 \let\@evenhead\@empty
 \def\@oddfoot{\it \hfill\today}%
 \let\@evenfoot\@oddfoot}
\makeatother

% A modified page layout
\textwidth 6.75in
\oddsidemargin -0.15in
\evensidemargin -0.15in
\textheight 9in
\topmargin -0.5in


\usepackage{microtype}
\usepackage{fancyhdr}
\pagestyle{fancy}
\pagenumbering{arabic}

\usepackage{listings}
\lstnewenvironment{code}{\lstset{language=Haskell,basicstyle=\small\ttfamily}}{}


\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}


%%% Syntax Highlighting for code  %%%
%%% Adapted from knitr book %%% 
\usepackage{fancyvrb}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\newenvironment{Shaded}{}{}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{{#1}}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{{#1}}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{{#1}}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{{#1}}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{{#1}}}
\newcommand{\RegionMarkerTok}[1]{{#1}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}}
\newcommand{\NormalTok}[1]{{#1}}
\usepackage{enumerate}
\usepackage{ctable}
\usepackage{float}

% This is needed because raggedright in table elements redefines \\:
\newcommand{\PreserveBackslash}[1]{\let\temp=\\#1\let\\=\temp}
\let\PBS=\PreserveBackslash
\usepackage[normalem]{ulem}
\newcommand{\textsubscr}[1]{\ensuremath{_{\scriptsize\textrm{#1}}}}

% Configure hyperlinks package
\usepackage[breaklinks=true,linktocpage,pdftitle={rfishbase: exploring, manipulating and visualizing FishBase data from R},pdfauthor={},xetex,colorlinks]{hyperref}
\hypersetup{breaklinks=true, pdfborder={0 0 0}}

% Pandoc toggle for numbering sections (defaults to be off)
\setcounter{secnumdepth}{0}


\VerbatimFootnotes % allows verbatim text in footnotes

% Pandoc header



\begin{document}
\begin{frontmatter}
  \title{rfishbase: exploring, manipulating and visualizing FishBase data from R}
  \author[cpb]{Carl Boettiger\corref{cor1}}
  \author[stats]{Duncan Temple Lang}
  \author[cpb]{Peter C. Wainwright}
  \ead{cboettig@ucdavis.edu}
  \cortext[cor1]{Corresponding author, cboettig@ucdavis.edu}
  \address[cpb]{Center for Population Biology, University of California, Davis, California 95616}
  \address[stats]{Department of Statistics, University of California, Davis, California 95616}
 \end{frontmatter}


\section{Abstract}

This paper introduces a package that provides interactive and
programmatic access to the FishBase repository. This package allows one
to interact with data on over 30,000 fish species in the rich
statistical computing environment, \texttt{R}. This direct, scriptable
interface to FishBase data enables better discovery and integration
essential for large-scale comparative analyses. The paper provides
several examples to illustrate how the package works, and how it can be
integrated into phylogenetics packages such as~\texttt{ape} and
\texttt{geiger}.

\subparagraph{keywords}

R \textbar{} vignette \textbar{} fishbase

\section{Introduction}

FishBase (\href{http://fishbase.org}{fishbase.org}) is an award-winning
online database of information about the morphology, trophic ecology,
physiology, ecotoxicology, reproduction and economic relevance of the
world's fishes, organized by species~(Froese and Pauly 2012). This
repository of information has proven to be a profoundly valuable
community resource and the data has the potential to be used in a wide
range of studies. However, assembling subsets of data housed in FishBase
for use in focused analyses can be tedious and time-consuming. To
facilitate the extraction, visualization, and integration of this data,
the \texttt{rfishbase} package was been written for the R language for
statistical computing and graphics (R Development Core Team 2012). R is
a freely available open source computing environment that is used
extensively in ecological research, with a large collection of packages
built explicitly for this purpose (Kneib 2007).

The \texttt{rfishbase} package is dynamically updated from the FishBase
database, describe its functions for extracting, manipulating and
visualizing data, and then illustrate how these functions can be
combined for more complicated analyses. Lastly it illustrates how having
access to FishBase data through R allows a user to interface with other
resources such as comparative phylogenetics software. The purpose of
this paper is to introduce \texttt{rfishbase} and illustrate core
features of its functionality.

\section{Accessing FishBase data from R}

In addition to its web-based interface, FishBase provides machine
readable XML files for 30,622 (as accessed on 14 May, 2012) of its
species entries to facilitate programmatic access of the data housed in
this resource. As complete downloads of the FishBase database are not
available, the FishBase team encouraged us to use these XML files as an
entry point for programmatic access. We have introduced caching and
pausing features into the package to prevent access from over-taxing the
FishBase servers.\\While FishBase encourages the use of its data by
programmatic access, (Froese, pers. comm), users of \texttt{rfishbase}
should respect these load-limiting functions, and provide appropriate
acknowledgment. A more detailed discussion of incentives, ethics, and
legal requirements in sharing and accessing such repositories can be
found in the respective literature, \emph{e.g.} Fisher and Fortmann
(2010) or Costello (2009).

The \texttt{rfishbase} package works by creating a cached copy of all
data on FishBase currently available in XML format on the FishBase
webpages. This process relies on the RCurl (Lang 2012a) and XML (Lang
2012b) packages to access these pages and parse the resulting XML into a
local cache. Caching increases the speed of queries and greatly reduces
demands on the FishBase server, which in its present form is not built
to support direct access to application programming interfaces (APIs). A
cached copy is included in the package and can be loaded in to R using
the command:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{data}\NormalTok{(fishbase) }
\end{Highlighting}
\end{Shaded}
This loads a copy of all available data from FishBase into the R list,
\texttt{fish.data}, which can be passed to the various functions of
\texttt{rfishbase} for extraction, manipulation and visualization. The
online repository is frequently updated as new information is uploaded.
To get the most recent copy of FishBase, update the cache instead. The
update may take up to 24 hours. This copy is stored in the specified
directory (note that ``.'' can be used to indicate the current working
directory) with the current date. The most recent copy of the data in
the specified path can be loaded with the \texttt{loadCache()}
function.\\If no cached set is found, \texttt{rfishbase} will load the
copy originally included in the package.

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{updateCache}\NormalTok{(}\StringTok{"."}\NormalTok{)}
\KeywordTok{loadCache}\NormalTok{(}\StringTok{"."}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Loading the database creates an object called fish.data, with one entry
per fish species for which data was successfully found, for a total of
30,622 species.

Not all the data available in FishBase is included in these
machine-readable XML files. Consequently, \texttt{rfishbase} returns
taxonomic information, trophic description, habitat, distribution, size,
life-cycle, morphology and diagnostic information. The information
returned in each category is provided as plain-text, consequently
\texttt{rfishbase} must use regular expression matching to identify the
occurrence of particular words or patterns in this text corresponding to
data of interest (Friedl 2006). Any regular expression can be used in in
search queries. While these expressions allows for very precise pattern
matching, applying this approach to plain text runs some risk of error
which should not be ignored. Visual inspection of matches and careful
construction of these expressions can help mitigate this risk. We
provide example functions for reliably matching several quantitative
traits from these text-based descriptions, which can be used as a basis
for writing functions to identify other terms of interest.

Quantitative traits such as standard length, maximum known age, spine
and ray counts, and depth information are provided consistently for most
species, allowing \texttt{rfishbase} to extract this data directly.
Other queries require pattern matching. While simple text searches
within a given field are usually reliable, the \texttt{rfishbase} search
functions will take any regular expression query, which permits logical
matching, identification of number strings, and much more. The
interested user should consult a reference on regular expressions after
studying the simple examples provided here to learn more.

\section{Tools for data extraction, analysis, and visualization}

The basic tool for data extraction in \texttt{rfishbase} is the
\texttt{which\_fish()} function. This function takes a list of FishBase
data (usually the entire database, \texttt{fish.data}, or a subset
thereof, as illustrated later) and returns an array of those species
matching the query. This array is given as a list of true/false values
for every species in the query. This return structure has several
advantages which are illustrated below.

Here is a query for reef-associated fish (mention of ``reef'' in the
habitat description), and second query for fish that have ``nocturnal''
in their trophic description:

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{reef <- }\KeywordTok{which_fish}\NormalTok{(}\StringTok{"reef"}\NormalTok{, }\StringTok{"habitat"}\NormalTok{, fish.data)}
\NormalTok{nocturnal <- }\KeywordTok{which_fish}\NormalTok{(}\StringTok{"nocturnal"}\NormalTok{, }\StringTok{"trophic"}\NormalTok{, fish.data)}
\end{Highlighting}
\end{Shaded}
One way these returned values are commonly used is to obtain a subset of
the database that meets this criteria, which can then be passed on to
other functions. For instance, if one wants the scientific names of
these reef fish, one can use the \texttt{fish\_names} function. Like the
\texttt{which\_fish} function, it takes the list of FishBase data,
\texttt{fish.data} as input. In this example, just the subset that are
reef affiliated are passed to the function,

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{reef_species <- }\KeywordTok{fish_names}\NormalTok{(fish.data[reef])}
\end{Highlighting}
\end{Shaded}
Because our \texttt{reef} object is a list of logical values
(true/false), one can combine this in intuitive ways with other queries.
For instance, one can query for the names of all fish that are both
nocturnal and not reef associated,

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{nocturnal_nonreef_orders <- }\KeywordTok{fish_names}\NormalTok{(fish.data[nocturnal & !reef], }\StringTok{"Class"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Note that in this example, it is also specified that the user wants the
taxonomic Class of the fish matching the query, rather than the species
names. \texttt{fish\_names} will allow the user to specify any taxonomic
level for it to return. Quantitative trait queries work in a similar
manner to \texttt{fish\_names}, taking the FishBase data and returning
the requested information. For instance, the function \texttt{getSize}
returns the length (default), weight, or age of the fish in the query:

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{age <- }\KeywordTok{getSize}\NormalTok{(fish.data, }\StringTok{"age"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\texttt{rfishbase} can also extract a table of quantitative traits from
the morphology field, describing the number of vertebrate, dorsal and
anal fin spines and rays,

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{morphology_numbers <- }\KeywordTok{getQuantTraits}\NormalTok{(fish.data)}
\end{Highlighting}
\end{Shaded}
and extract the depth range (extremes and usual range) from the habitat
field,

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{depths <- }\KeywordTok{getDepth}\NormalTok{(fish.data)}
\end{Highlighting}
\end{Shaded}
A list of all the functions provided by \texttt{rfishbase} can be found
in Table 1.\\The \texttt{rfishbase} manual provided with the package
provides more detail about each of these functions, together with
examples for their use.

\begin{table}[ht]
\begin{center}
\begin{tabular}{ll}
  \hline
function.name & description \\ 
  \hline
familySearch & A function to find all fish that are members of \\ 
   & a scientific Family \\ 
  findSpecies & Returns the matching indices in the data given \\ 
   & a list of species names \\ 
  fish.data & A cached copy of extracted FishBase data, \\ 
   & 03/2012. \\ 
  fish\_names & Return the scientific names, families, classes, \\ 
   & or orders of the input data \\ 
  getDepth & Returns available depth range data \\ 
  getQuantTraits & Returns all quantitative trait values found in \\ 
   & the morphology data \\ 
  getRefs & Returns the FishBase reference id numbers \\ 
   & matching a query. \\ 
  getSize & Returns available size data of specified type \\ 
   & (length, weight, or age) \\ 
  habitatSearch & A function to search for the occurances of any \\ 
   & keyword in habitat description \\ 
  labridtree & An example phylogeny of labrid fish \\ 
  loadCache & Load an updated cache \\ 
  updateCache & Update the cached copy of fishbase data \\ 
  which\_fish & which\_fish is the the generic search function \\ 
   & for fishbase a variety of description types \\ 
   \hline
\end{tabular}
\caption{A list of each of the functions and data objects provided by rfishbase}
\end{center}
\end{table}

The real power of programmatic access is the ease with which one can
combine, visualize, and statistically test a custom compilation of this
data. To do so it is useful to organize a collection of queries into a
data frame. The next set of commands combines the queries made above and
a few additional queries into a data frame in which each row represents
a species and each column represents a variable.

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{marine <- }\KeywordTok{which_fish}\NormalTok{(}\StringTok{"marine"}\NormalTok{, }\StringTok{"habitat"}\NormalTok{, fish.data)}
\NormalTok{africa <- }\KeywordTok{which_fish}\NormalTok{(}\StringTok{"Africa:"}\NormalTok{, }\StringTok{"distribution"}\NormalTok{, fish.data)}
\NormalTok{length <- }\KeywordTok{getSize}\NormalTok{(fish.data, }\StringTok{"length"}\NormalTok{)}
\NormalTok{order <- }\KeywordTok{fish_names}\NormalTok{(fish.data, }\StringTok{"Order"}\NormalTok{)}
\NormalTok{dat <- }\KeywordTok{data.frame}\NormalTok{(reef, nocturnal,  age, marine, africa, length, order)}
\end{Highlighting}
\end{Shaded}
This data frame contains categorical data (\emph{e.g.} is the fish a
carnivore) and continuous data (\emph{e.g.} weight or age of fish). One
can take advantage of data visualization tools in R to begin exploring
this data. These examples are simply meant to be illustrative of the
kinds of analysis possible and how they would be constructed.

For instance, one can identify which orders contain the greatest number
of species, and for each of them, plot the fraction in which the species
are marine.

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{biggest <- }\KeywordTok{names}\NormalTok{(}\KeywordTok{head}\NormalTok{(}\KeywordTok{sort}\NormalTok{(}\KeywordTok{table}\NormalTok{(order),}\DataTypeTok{decr=}\NormalTok{T), }\DecValTok{8}\NormalTok{))}
\NormalTok{primary_orders <- }\KeywordTok{subset}\NormalTok{(dat, order %in% biggest)}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(primary_orders, }\KeywordTok{aes}\NormalTok{(order, }\DataTypeTok{fill=}\NormalTok{marine)) + }\KeywordTok{geom_bar}\NormalTok{() + }
\CommentTok{# a few commands to customize appearance }
  \KeywordTok{geom_bar}\NormalTok{(}\DataTypeTok{colour=}\StringTok{"black"}\NormalTok{,}\DataTypeTok{show_guide=}\OtherTok{FALSE}\NormalTok{) +  }
  \KeywordTok{opts}\NormalTok{(}\DataTypeTok{axis.text.x=}\KeywordTok{theme_text}\NormalTok{(}\DataTypeTok{angle=}\DecValTok{90}\NormalTok{, }\DataTypeTok{hjust=}\DecValTok{1}\NormalTok{, }\DataTypeTok{size=}\DecValTok{6}\NormalTok{)) + }
  \KeywordTok{opts}\NormalTok{(}\DataTypeTok{legend.title=}\KeywordTok{theme_blank}\NormalTok{(), }\DataTypeTok{legend.justification=}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{0}\NormalTok{), }\DataTypeTok{legend.position=}\KeywordTok{c}\NormalTok{(.}\DecValTok{9}\NormalTok{,.}\DecValTok{6}\NormalTok{)) +}
  \KeywordTok{scale_fill_grey}\NormalTok{(}\DataTypeTok{labels=}\KeywordTok{c}\NormalTok{(}\StringTok{"Marine"}\NormalTok{, }\StringTok{"Non-marine"}\NormalTok{)) + }
  \KeywordTok{xlab}\NormalTok{(}\StringTok{""}\NormalTok{) + }\KeywordTok{ylab}\NormalTok{(}\StringTok{"Number of species"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{figure}[htbp]
\centering
\includegraphics{figure/Figure1.pdf}
\caption{Fraction of marine species in the eight largest orders of
teleost fishes}
\end{figure}

FishBase data excels for comparative studies across many species, but
searching through over 30,000 species to extract data makes broad
comparative analyses quite time-consuming. Having access to the data in
R, one can answer such questions as fast as they are posed. Consider
looking for a correlation between the maximum age and the size of fish.
One can partition the data by any variable of interest as well -- this
example color codes the points based on whether or not the species is
marine-associated. The \texttt{ggplot2} package (Wickham 2009) provides
a particularly powerful and flexible language for visual exploration of
such patterns.

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(dat,}\KeywordTok{aes}\NormalTok{(age, length, }\DataTypeTok{shape=}\NormalTok{marine)) +}
  \KeywordTok{geom_point}\NormalTok{(}\DataTypeTok{position=}\StringTok{'jitter'}\NormalTok{, }\DataTypeTok{size=}\DecValTok{1}\NormalTok{) +}
  \KeywordTok{scale_y_log10}\NormalTok{() + }\KeywordTok{scale_x_log10}\NormalTok{(}\DataTypeTok{breaks=}\KeywordTok{c}\NormalTok{(}\DecValTok{50}\NormalTok{,}\DecValTok{100}\NormalTok{,}\DecValTok{200}\NormalTok{)) +}
  \KeywordTok{scale_shape_manual}\NormalTok{(}\DataTypeTok{values=}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{19}\NormalTok{), }\DataTypeTok{labels=}\KeywordTok{c}\NormalTok{(}\StringTok{"Marine"}\NormalTok{, }\StringTok{"Non-marine"}\NormalTok{)) + }
  \KeywordTok{ylab}\NormalTok{(}\StringTok{"Standard length (cm)"}\NormalTok{) + }\KeywordTok{xlab}\NormalTok{(}\StringTok{"Maximum observed age (years)"}\NormalTok{) +}
  \KeywordTok{opts}\NormalTok{(}\DataTypeTok{legend.title=}\KeywordTok{theme_blank}\NormalTok{(), }\DataTypeTok{legend.justification=}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{0}\NormalTok{), }\DataTypeTok{legend.position=}\KeywordTok{c}\NormalTok{(.}\DecValTok{9}\NormalTok{,}\DecValTok{0}\NormalTok{)) +}
  \KeywordTok{opts}\NormalTok{(}\DataTypeTok{legend.key =} \KeywordTok{theme_blank}\NormalTok{())}
\end{Highlighting}
\end{Shaded}
\begin{figure}[htbp]
\centering
\includegraphics{figure/Figure2.pdf}
\caption{Scatterplot maximum age with length observed in each species.
Color indicates marine or freshwater species.}
\end{figure}

A wide array of visual displays are available for different kinds of
data. A box-plot is a natural way to compare the distributions of
categorical variables, such as asking ``Are reef species longer lived
than non-reef species in the marine environment?''

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(}\KeywordTok{subset}\NormalTok{(dat, marine)) + }
  \KeywordTok{geom_boxplot}\NormalTok{(}\KeywordTok{aes}\NormalTok{(reef, age)) + }
  \KeywordTok{scale_y_log10}\NormalTok{() + }\KeywordTok{xlab}\NormalTok{(}\StringTok{""}\NormalTok{) +}
  \KeywordTok{ylab}\NormalTok{(}\StringTok{"Maximum observed age (years)"}\NormalTok{)  +}
  \KeywordTok{opts}\NormalTok{(}\DataTypeTok{axis.text.x =} \KeywordTok{theme_text}\NormalTok{(}\DataTypeTok{size =} \DecValTok{8}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{figure}[htbp]
\centering
\includegraphics{figure/Figure3.pdf}
\caption{Distribution of maximum age for reef-associated and non-reef
associated fish}
\end{figure}

In addition to powerful visualizations R provides an unparalleled array
of statistical analysis methods.\\Executing the linear model testing the
correlation of length with maximum size takes a single line,

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(MASS)}
\NormalTok{corr.model <- }\KeywordTok{summary}\NormalTok{(}\KeywordTok{rlm}\NormalTok{(}\DataTypeTok{data=}\NormalTok{dat,  length ~ age))}
\end{Highlighting}
\end{Shaded}
which shows a significant correlation between maximum age and standard
length (P = 0.001).

\subsection{Comparative studies}

Many ecological and evolutionary studies rely on comparisons between
taxa to pursue questions that cannot be approached experimentally. For
instance, recent studies have attempted to identify whether
reef-associated clades experience greater species diversification rates
than non-reef-associated groups (\emph{e.g.} Alfaro et al. 2009). One
can identify and compare the numbers of reef associated species in
different families using the \texttt{rfishbase} functions presented
above.

In this example, consider the simpler question ``Are there more
reef-associated species in \emph{Labridae} than in \emph{Gobiidae}?''
Recent research has shown that the families Scaridae and Odacidae are
nested within Labridae (Westneat and Alfaro 2005), although the three
groups are listed as separate families in fishbase. We get all the
species in fishbase from \emph{Labridae} (wrasses), \emph{Scaridae}
(parrotfishes) and \emph{Odacidae} (weed-whitings):

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{labrid <- }\KeywordTok{which_fish}\NormalTok{(}\StringTok{"(Labridae\textbar{}Scaridae\textbar{}Odacidae)"}\NormalTok{, }\StringTok{"Family"}\NormalTok{, fish.data)}
\end{Highlighting}
\end{Shaded}
and get all the species of gobies

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{goby <- }\KeywordTok{which_fish}\NormalTok{(}\StringTok{"Gobiidae"}\NormalTok{, }\StringTok{"Family"}\NormalTok{, fish.data)}
\end{Highlighting}
\end{Shaded}
Identify how many labrids are found on reefs

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{labrid.reef <- }\KeywordTok{which_fish}\NormalTok{(}\StringTok{"reef"}\NormalTok{, }\StringTok{"habitat"}\NormalTok{, fish.data[labrid])}
\NormalTok{labrids.on.reefs <- }\KeywordTok{table}\NormalTok{(labrid.reef)}
\end{Highlighting}
\end{Shaded}
and how many gobies are found on reefs:

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{gobies.on.reefs <- }\KeywordTok{table}\NormalTok{(}\KeywordTok{which_fish}\NormalTok{(}\StringTok{"reef"}\NormalTok{, }\StringTok{"habitat"}\NormalTok{, fish.data[goby]) )}
\end{Highlighting}
\end{Shaded}
Note that summing the list of true/false values returned gives the total
number of matches. This reveals that there are 505 labrid species
associated with reefs, and 401 goby species associated with reefs. This
example illustrates the power of accessing the FishBase data: Gobies are
routinely listed as the biggest group of reef fishes (\emph{e.g.}
Bellwood and Wainwright 2002) but this is because there are more species
in \emph{Gobiidae} than any other family of reef fish. When one counts
the species in each group that live on reefs one finds that labrids are
actually the most species-rich family on reefs.

\section{Integration of analyses}

One of the greatest advantages of accessing FishBase directly through R
is the ability to take advantage of other specialized analyses available
through R packages. Users familiar with these packages can more easily
take advantage of the data available on FishBase. This is illustrated
with an example that combines phylogenetic methods available in R with
quantitative trait data available from \texttt{rfishbase}.

This series of commands illustrates testing for a phylogenetically
corrected correlation between the observed length of a species and the
maximum observed depth at which it is found. One begins by reading in
the data for a phylogenetic tree of labrid fish (provided in the
package), and the phylogenetics packages \texttt{ape} (Paradis, Claude,
and Strimmer 2004) and \texttt{geiger} (Harmon et al. 2009).

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{data}\NormalTok{(labridtree)}
\KeywordTok{library}\NormalTok{(ape)}
\KeywordTok{library}\NormalTok{(geiger) }
\end{Highlighting}
\end{Shaded}
Find the species represented on this tree in FishBase

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{myfish <- }\KeywordTok{findSpecies}\NormalTok{(labridtree$tip.label, fish.data)}
\end{Highlighting}
\end{Shaded}
Get the maximum depth of each species and sizes of each species:

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{depths <- }\KeywordTok{getDepth}\NormalTok{(fish.data[myfish])[,}\StringTok{"deep"}\NormalTok{]}
\NormalTok{size <- }\KeywordTok{getSize}\NormalTok{(fish.data[myfish], }\StringTok{"length"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Drop missing data, and then drop tips from the phylogeny for which data
was not available:

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{data <- }\KeywordTok{na.omit}\NormalTok{(}\KeywordTok{data.frame}\NormalTok{(size,depths))}
\NormalTok{pruned <- }\KeywordTok{treedata}\NormalTok{(labridtree, data)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
Dropped tips from the tree because there were no matching names in the data:
 [1] "Anampses_geographicus"     "Bodianus_perditio"        
 [3] "Chlorurus_bleekeri"        "Choerodon_cephalotes"     
 [5] "Choerodon_venustus"        "Coris_batuensis"          
 [7] "Diproctacanthus_xanthurus" "Halichoeres_melanurus"    
 [9] "Halichoeres_miniatus"      "Halichoeres_nigrescens"   
[11] "Macropharyngodon_choati"   "Oxycheilinus_digrammus"   
[13] "Scarus_flavipectoralis"    "Scarus_rivulatus"         
\end{verbatim}
Use phylogenetically independent contrasts (Felsenstein 1985) to
determine if depth correlates with size after correcting for phylogeny:

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{corr.size <- }\KeywordTok{pic}\NormalTok{(pruned$data[[}\StringTok{"size"}\NormalTok{]],pruned$phy)}
\NormalTok{corr.depth <- }\KeywordTok{pic}\NormalTok{(pruned$data[[}\StringTok{"depths"}\NormalTok{]],pruned$phy)}
\NormalTok{corr.summary <- }\KeywordTok{summary}\NormalTok{(}\KeywordTok{lm}\NormalTok{(corr.depth ~ corr.size - }\DecValTok{1}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
which returns a non-significant correlation (p = 0.47).

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(}\KeywordTok{data.frame}\NormalTok{(corr.size,corr.depth), }\KeywordTok{aes}\NormalTok{(corr.size,corr.depth)) +}
 \KeywordTok{geom_point}\NormalTok{() + }\KeywordTok{stat_smooth}\NormalTok{(}\DataTypeTok{method=}\NormalTok{lm, }\DataTypeTok{col=}\DecValTok{1}\NormalTok{) + }
 \KeywordTok{xlab}\NormalTok{(}\StringTok{"Contrast of standard length (cm)"}\NormalTok{) +}
 \KeywordTok{ylab}\NormalTok{(}\StringTok{"Contrast maximum depth (m)"}\NormalTok{) + }\KeywordTok{opts}\NormalTok{(}\DataTypeTok{title=}\StringTok{"Phylogenetically standardized contrasts"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{figure}[htbp]
\centering
\includegraphics{figure/Figure4.pdf}
\caption{Correcting for phylogeny, size is not correlated with maximum
depth observed in labrids}
\end{figure}

One can also estimate different evolutionary models for these traits to
decide which best describes the data,

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{bm <- }\KeywordTok{fitContinuous}\NormalTok{(pruned$phy, pruned$data[[}\StringTok{"depths"}\NormalTok{]], }\DataTypeTok{model=}\StringTok{"BM"}\NormalTok{)[[}\DecValTok{1}\NormalTok{]]}
\NormalTok{ou <- }\KeywordTok{fitContinuous}\NormalTok{(pruned$phy, pruned$data[[}\StringTok{"depths"}\NormalTok{]], }\DataTypeTok{model=}\StringTok{"OU"}\NormalTok{)[[}\DecValTok{1}\NormalTok{]]}
\end{Highlighting}
\end{Shaded}
where the Brownian motion model has an AIC score of 1,185 while the OU
model has a score of~918.2, suggesting that OU is the better model.

\section{Discussion}

With more and more data readily available, informatics is becoming
increasingly important in ecology and evolution research (Jones et al.
2006), bringing new opportunities for research (Parr et al. 2011;
Michener and Jones 2012) while also raising new challenges (Reichman,
Jones, and Schildhauer 2011). It is in this spirit that the
\texttt{rfishbase} package provides programmatic access to the data
available on the already widely recognized database, FishBase. Such
tools allow researchers to take greater advantage of the data available,
facilitating deeper and richer analyses than would be feasible under
only manual access to the data. The examples in this manuscript are
intended to illustrate how this package works, and to help inspire
readers to consider and explore questions that would otherwise be too
time consuming or challenging to pursue. This paper has introduced the
functions of the \texttt{rfishbase} package and described how they can
be used to improve the extraction, visualization, and integration of
FishBase data in ecological and evolutionary research.

\subsection{The self-updating study}

Because analyses using this data are written in R scripts, it becomes
easy to update the results as more data becomes available on FishBase.
Programmatic access to data coupled with script-able analyses can help
ensure that research is more easily reproduced and also facilitate
extending the work in future studies (Peng 2011; Merali 2010). This
document is an example of this, using a dynamic documentation
interpreter program which runs the code displayed to produce the results
shown, decreasing the possibility for faulty code (Xie 2012). As
FishBase is updated, one can regenerate these results with less missing
data. Readers can find the original document which combines the
source-code and text on the project's
\href{https://github.com/ropensci/rfishbase/tree/master/inst/doc/rfishbase}{Github
page}.

\subsection{Limitations and future directions}

FishBase contains much data that has not been made accessible in
machine-readable XML format. The authors are in contact with the
database managers and look forward to providing access to additional
types of data as they become available. Because most of the data
provided in the XML comes as plain text rather that being identified
with machine-readable tags, reliability of the results is limited by
text matching.\\Improved text matching queries could provide more
reliable information, and facilitate other specialized queries such as
extracting geographic distribution details as categorical variables or
latitude/longitude coordinates. FishBase taxonomy is inconsistent with
taxonomy provided elsewhere, and additional package functions could help
resolve these differences in assignments.

\texttt{rfishbase} has been available to R users through the
\href{http://cran.r-project.org/web/packages/rfishbase/}{Comprehensive R
Archive Network} since October 2011, and has a growing user base. The
project remains in active development to evolve with the needs of its
users. Users can view the most recent changes and file issues with the
package on its development website on Github,
(\href{https://github.com/ropensci/rfishbase}{https://github.com/ropensci/rfishbase})
and developers can submit changes to the code or adapt it into their own
software.

Programmers of other R software packages can make use of the
\texttt{rfishbase} package to make this data available to their
functions, further increasing the use and impact of FishBase. For
instance, the project \href{http://OpenFisheries.org}{OpenFisheries}
makes use of the \texttt{rfishbase} package to provide information about
commercially relevant species.

\section{Acknowledgements}

This work was supported by a Computational Sciences Graduate Fellowship
from the Department of Energy under grant number DE-FG02-97ER25308 to CB
and National Science Foundation grant DEB-1061981 to PCW. The
\texttt{rfishbase} package is part of the rOpenSci project
(\href{http://ropensci.org}{ropensci.org}).

\section{References}

Alfaro, Michael E., Francesco Santini, Chad D. Brock, Hugo Alamillo,
Alex Dornburg, Daniel L. Rabosky, Giorgio Carnevale, and Luke J. Harmon.
2009. ``Nine exceptional radiations plus high turnover explain species
diversity in jawed vertebrates.'' \emph{Proceedings of the National
Academy of Sciences} 106 (aug): 13410--14. doi:10.1073/pnas.0811087106.
\href{http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=2715324\textbackslash{}\&tool=pmcentrez\textbackslash{}\&rendertype=abstract}{http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=2715324\textbackslash{}\&tool=pmcentrez\textbackslash{}\&rendertype=abstract}.

Bellwood, D. R., and Peter C. Wainwright. 2002. ``The history and
biogeography of fishes on coral reefs.'' In \emph{Coral Reef Fishes.
Dynamics and diversity in a complex ecosystem}, ed. P. F. Sale, 5--32.
San Diego: Academic Press.

Costello, Mark J. 2009. ``Motivating Online Publication of Data.''
\emph{BioScience} 59 (may): 418--427. doi:10.1525/bio.2009.59.5.9.
\href{http://caliber.ucpress.net/doi/abs/10.1525/bio.2009.59.5.9 http://www.jstor.org/stable/25502450}{http://caliber.ucpress.net/doi/abs/10.1525/bio.2009.59.5.9
http://www.jstor.org/stable/25502450}.

Felsenstein, Joseph. 1985. ``Phylogenies and the Comparative Method.''
\emph{The American Naturalist} 125 (jan): 1--15. doi:10.1086/284325.
\href{http://www.journals.uchicago.edu/doi/abs/10.1086/284325}{http://www.journals.uchicago.edu/doi/abs/10.1086/284325}.

Fisher, Joshua B., and Louise Fortmann. 2010. ``Governing the data
commons: Policy, practice, and the advancement of science.''
\emph{Information \& Management} 47 (may): 237--245.
doi:10.1016/j.im.2010.04.001.
\href{http://linkinghub.elsevier.com/retrieve/pii/S0378720610000376}{http://linkinghub.elsevier.com/retrieve/pii/S0378720610000376}.

Friedl, Jeffrey E. F. 2006. \emph{Mastering regular expressions}.
O'Reilly Media, Inc..
\href{http://books.google.com/books?id=NYEX-Q9evKoC\textbackslash{}\&pgis=1}{http://books.google.com/books?id=NYEX-Q9evKoC\textbackslash{}\&pgis=1}.

Froese, R., and Daniel Pauly. 2012. ``FishBase.'' World Wide Web
electronic publication.. \href{www.fishbase.org}{www.fishbase.org}.

Harmon, Luke, Jason Weir, Chad Brock, Rich Glor, Wendell Challenger, and
Gene Hunt. 2009. ``geiger: Analysis of evolutionary diversification.''
\href{http://cran.r-project.org/package=geiger}{http://cran.r-project.org/package=geiger}.

Jones, Matthew B., Mark P. Schildhauer, O. J. Reichman, and Shawn
Bowers. 2006. ``The New Bioinformatics: Integrating Ecological Data from
the Gene to the Biosphere.'' \emph{Annual Review of Ecology, Evolution,
and Systematics} 37 (dec): 519--544.
doi:10.1146/annurev.ecolsys.37.091305.110031.
\href{http://arjournals.annualreviews.org/doi/abs/10.1146/annurev.ecolsys.37.091305.110031}{http://arjournals.annualreviews.org/doi/abs/10.1146/annurev.ecolsys.37.091305.110031}.

Kneib, Thomas. 2007. ``Introduction to the Special Volume on 'Ecology
and Ecological Modelling in R'.'' \emph{Journal of Statistical Software}
22: 1--7.
\href{http://www.jstatsoft.org/v22/i01/paper}{http://www.jstatsoft.org/v22/i01/paper}.

Lang, Duncan Temple. 2012a. ``RCurl: General network (HTTP/FTP/...)
client interface for R.''
\href{http://cran.r-project.org/package=RCurl}{http://cran.r-project.org/package=RCurl}.

---------. 2012b. ``XML: Tools for parsing and generating XML within R
and S-Plus.''
\href{http://cran.r-project.org/package=XML}{http://cran.r-project.org/package=XML}.

Merali, Zeeya. 2010. ``Why Scientific programming does not compute.''
\emph{Nature}: 6--8.

Michener, William K., and Matthew B. Jones. 2012. ``Ecoinformatics:
supporting ecology as a data-intensive science.'' \emph{Trends in
Ecology \& Evolution} 27 (jan): 85--93. doi:10.1016/j.tree.2011.11.016.
\href{http://linkinghub.elsevier.com/retrieve/pii/S0169534711003399}{http://linkinghub.elsevier.com/retrieve/pii/S0169534711003399}.

Paradis, E., J. Claude, and K. Strimmer. 2004. ``APE: analyses of
phylogenetics and evolution in R language.'' \emph{Bioinformatics} 20:
289--290.

Parr, Cynthia S., Robert Guralnick, Nico Cellinese, and Roderic D. M.
Page. 2011. ``Evolutionary informatics: unifying knowledge about the
diversity of life.'' \emph{Trends in ecology \& evolution} 27 (dec):
94--103. doi:10.1016/j.tree.2011.11.001.
\href{http://www.ncbi.nlm.nih.gov/pubmed/22154516}{http://www.ncbi.nlm.nih.gov/pubmed/22154516}.

Peng, R. D. 2011. ``Reproducible Research in Computational Science.''
\emph{Science} 334 (dec): 1226--1227. doi:10.1126/science.1213847.
\href{http://www.sciencemag.org/cgi/doi/10.1126/science.1213847}{http://www.sciencemag.org/cgi/doi/10.1126/science.1213847}.

R Development Core Team, The. 2012. ``R: A language and environment for
statistical computing.'' Vienna, Austria: R Foundation for Statistical
Computing. \href{http://www.r-project.org/}{http://www.r-project.org/}.

Reichman, O. J., Matthew B. Jones, and Mark P. Schildhauer. 2011.
``Challenges and Opportunities of Open Data in Ecology.'' \emph{Science}
331 (feb): 703--705. doi:10.1126/science.1197962.
\href{http://www.sciencemag.org/cgi/doi/10.1126/science.1197962 http://www.ncbi.nlm.nih.gov/pubmed/21311007}{http://www.sciencemag.org/cgi/doi/10.1126/science.1197962
http://www.ncbi.nlm.nih.gov/pubmed/21311007}.

Westneat, Mark W., and Michael E. Alfaro. 2005. ``Phylogenetic
relationships and evolutionary history of the reef fish family
Labridae.'' \emph{Molecular phylogenetics and evolution} 36 (aug):
370--90. doi:10.1016/j.ympev.2005.02.001.
\href{http://www.ncbi.nlm.nih.gov/pubmed/15955516}{http://www.ncbi.nlm.nih.gov/pubmed/15955516}.

Wickham, Hadley. 2009. \emph{ggplot2: elegant graphics for data
analysis}. Springer New York.
\href{http://had.co.nz/ggplot2/book}{http://had.co.nz/ggplot2/book}.

Xie, Yihui. 2012. ``knitr: A general-purpose package for dynamic report
generation in R.''
\href{http://yihui.name/knitr/}{http://yihui.name/knitr/}.


\bibliography{}


\end{document}
