% -*- mode: noweb; noweb-default-code-mode: R-mode; -*-
%\VignetteIndexEntry{Introduction to ordination in vegan}
\documentclass[a4paper,10pt]{article}
\usepackage{vegan} % vegan settings

\title{Vegan: an introduction to ordination} 
\author{Jari Oksanen}

\date{\footnotesize{
  processed with vegan
2.3-1
in R Under development (unstable) (2015-09-24 r69424) on \today}}

%% need no \usepackage{Sweave}
\begin{document}



\maketitle
\begin{abstract}
  The document describes typical, simple work pathways of
  vegetation ordination. Unconstrained ordination uses as examples
  detrended correspondence analysis and non-metric multidimensional
  scaling, and shows how to interpret their results by fitting
  environmental vectors and factors or smooth environmental surfaces
  to the graph. The basic plotting command, and more advanced plotting
  commands for congested plots are also discussed, as well as adding
  items such as ellipses, convex hulls, and other items for
  classes. The constrained ordination uses constrained (canonical)
  correspondence analysis as an example. It is first shown how a model
  is defined, then the document discusses model building and
  signficance tests of the whole analysis, single constraints and
  axes.
\end{abstract}
\tableofcontents

\vspace{3ex}
\noindent \pkg{Vegan} is a package for community ecologists.  This
documents explains how the commonly used ordination methods can be
performed in \pkg{vegan}.  The document only is a very basic
introduction.  Another document (\emph{vegan tutorial})
(\url{http://cc.oulu.fi/~jarioksa/opetus/method/vegantutor.pdf}) gives
a longer and more detailed introduction to ordination.  The
current document only describes a small part of all \pkg{vegan}
functions.  For most functions, the canonical references are the
\pkg{vegan} help pages, and some of the most important additional
functions are listed at this document.

\section{Ordination}

The \pkg{vegan} package contains all common ordination methods:
Principal component analysis (function \code{rda}, or \code{prcomp} in
the base \proglang{R}), correspondence analysis (\code{cca}),
detrended correspondence analysis (\code{decorana}) and a wrapper for
non-metric multidimensional scaling (\code{metaMDS}).  Functions
\code{rda} and \code{cca} mainly are designed for constrained
ordination, and will be discussed later.  In this chapter I describe
functions \code{decorana} and \code{metaMDS}.

\subsection{Detrended correspondence analysis}


Detrended correspondence analysis (\textsc{dca}) is done like this:
\begin{Schunk}
\begin{Sinput}
> library(vegan)
> data(dune)
> ord <- decorana(dune)
\end{Sinput}
\end{Schunk}
This saves ordination results in \code{ord}:
\begin{Schunk}
\begin{Sinput}
> ord
\end{Sinput}
\begin{Soutput}
Call:
decorana(veg = dune) 

Detrended correspondence analysis with 26 segments.
Rescaling of axes with 4 iterations.

                  DCA1   DCA2    DCA3    DCA4
Eigenvalues     0.5117 0.3036 0.12125 0.14267
Decorana values 0.5360 0.2869 0.08136 0.04814
Axis lengths    3.7004 3.1166 1.30055 1.47888
\end{Soutput}
\end{Schunk}
The display of results is very brief: only eigenvalues and used
options are listed.  Actual ordination results are not shown, but you
can see them with command \code{summary(ord)}, or extract the scores
with command \code{scores}.  The \code{plot} function also
automatically knows how to access the scores.

\subsection{Non-metric multidimensional scaling}


Function \code{metaMDS} is a bit special case.  The actual ordination
is performed by function \pkg{vegan} function \code{monoMDS} (or
alternatively using \code{isoMDS} of the \pkg{MASS} package).
Function \code{metaMDS} is a wrapper to perform non-metric
multidimensional scaling (\textsc{nmds}) like recommended in community
ordination: it uses adequate dissimilarity measures (function
\code{vegdist}), then it runs \textsc{nmds} several times with random
starting configurations, compares results (function
\code{procrustes}), and stops after finding twice a similar minimum
stress solution.  Finally it scales and rotates the solution, and adds
species scores to the configuration as weighted averages (function
\code{wascores}):
\begin{Schunk}
\begin{Sinput}
> ord <- metaMDS(dune)
\end{Sinput}
\begin{Soutput}
Run 0 stress 0.1192678 
Run 1 stress 0.1192678 
... New best solution
... procrustes: rmse 4.211892e-05  max resid 0.0001225318 
*** Solution reached
\end{Soutput}
\begin{Sinput}
> ord
\end{Sinput}
\begin{Soutput}
Call:
metaMDS(comm = dune) 

global Multidimensional Scaling using monoMDS

Data:     dune 
Distance: bray 

Dimensions: 2 
Stress:     0.1192678 
Stress type 1, weak ties
Two convergent solutions found after 1 tries
Scaling: centring, PC rotation, halfchange scaling 
Species: expanded scores based on ‘dune’ 
\end{Soutput}
\end{Schunk}

\section{Ordination graphics}

Ordination is nothing but a way of drawing graphs, and it is best to
inspect ordinations only graphically (which also implies that they
should not be taken too seriously).

All ordination results of \pkg{vegan} can be displayed with a
\code{plot} command (Fig. \ref{fig:plot}):
\begin{Schunk}
\begin{Sinput}
> plot(ord)
\end{Sinput}
\end{Schunk}
\begin{figure}
\includegraphics{intro-vegan-006}
\caption{Default ordination plot.}
\label{fig:plot}
\end{figure}
Default \code{plot} command uses either black circles for sites and
red pluses for species, or black and red text for sites and species,
resp.  The choices depend on the number of items in the plot and
ordination method.  You can override the default choice by setting
\code{type = "p"} for points, or \code{type = "t"} for text.  For
a better control of ordination graphics you can first draw an empty
plot (\code{type = "n"}) and then add species and sites separately
using \code{points} or \code{text} functions.  In this way you can
combine points and text, and you can select colours and character
sizes freely (Fig. \ref{fig:plot.args}):
\begin{Schunk}
\begin{Sinput}
> plot(ord, type = "n")
> points(ord, display = "sites", cex = 0.8, pch=21, col="red", bg="yellow")
> text(ord, display = "spec", cex=0.7, col="blue")
\end{Sinput}
\end{Schunk}
\begin{figure}
\includegraphics{intro-vegan-008}
\caption{A more colourful ordination plot where sites are points, and
  species are text.}
\label{fig:plot.args}
\end{figure}

All \pkg{vegan} ordination methods have a specific \code{plot}
function.  In addition, \pkg{vegan} has an alternative plotting
function \code{ordiplot} that also knows many non-\pkg{vegan}
ordination methods, such as \code{prcomp}, \code{cmdscale} and
\code{isoMDS}.  All \pkg{vegan} plot functions return invisibly
an \code{ordiplot} object, so that you can use \code{ordiplot}
support functions with the results (\code{points}, \code{text},
\code{identify}).

Function \code{ordirgl} (requires \pkg{rgl} package) provides
dynamic three-dimensional graphics that can be spun around or zoomed
into with your mouse.  Function \pkg{ordiplot3d} (requires package
\code{scatterplot3d}) displays simple three-dimensional
scatterplots.

\subsection{Cluttered plots}

Ordination plots are often congested: there is a large number of sites
and species, and it may be impossible to display all clearly.  In
particular, two or more species may have identical scores and are
plotted over each other.  \pkg{Vegan} does not have (yet?)
automatic tools for clean plotting in these cases, but here some
methods you can try:
\begin{itemize}
\item Zoom into graph setting axis limits \code{xlim} and
  \code{ylim}.  You must typically set both, because \pkg{vegan}
  will maintain equal aspect ratio of axes.
\item Use points and add labell only some points with \code{identify}
  command.
\item Use \code{select} argument in ordination \code{text} and
  \code{points} functions to only show the specified items.
\item Use \code{ordilabel} function that uses opaque background to
  the text: some text labels will be covered, but the uppermost are
  readable.
\item Use automatic \code{orditorp} function that uses text only if
  this can be done without overwriting previous labels, but points in
  other cases.
\item Use automatic \code{ordipointlabel} function that uses both
  points and text labels, and tries to optimize the location of the
  text to avoid overwriting.
\item Use interactive \code{orditkplot} function that draws both
  points and labels for ordination scores, and allows you to drag
  labels to better positions. You can export the results of the edited
  graph to encapsulated \proglang{postscript}, \proglang{pdf},
  \proglang{png} or \proglang{jpeg} files, or copy directly to
  encapsulated \proglang{postscript}, or return the edited positions
  to \proglang{R} for further processing.
\end{itemize}

\subsection{Adding items to ordination plots}

\pkg{Vegan} has a group of functions for adding information about
classification or grouping of points onto ordination diagrams.
Function \code{ordihull} adds convex hulls, \code{ordiellipse}
adds ellipses of standard deviation, standard error or confidence
areas, and \code{ordispider} combines items to their centroid
(Fig. \ref{fig:ordihull}):
\begin{Schunk}
\begin{Sinput}
> data(dune.env)
> attach(dune.env)
\end{Sinput}
\end{Schunk}
\begin{Schunk}
\begin{Sinput}
> plot(ord, disp="sites", type="n")
> ordihull(ord, Management, col="blue")
> ordiellipse(ord, Management, col=3,lwd=2)
> ordispider(ord, Management, col="red", label = TRUE)
> points(ord, disp="sites", pch=21, col="red", bg="yellow", cex=1.3)
\end{Sinput}
\end{Schunk}
\begin{figure}
\includegraphics{intro-vegan-011}
\caption{Convex hull, standard error ellipse and a spider web diagram
  for Management levels in ordination.}
\label{fig:ordihull}
\end{figure}
In addition, you can overlay a cluster dendrogram from \code{hclust}
using \code{ordicluster} or a minimum spanning tree from
\code{spantree} with its \code{lines} function.  Segmented arrows
can be added with \code{ordiarrows}, lines with
\code{ordisegments} and regular grids with \code{ordigrid}.

\section{Fitting environmental variables}

\pkg{Vegan} provides two functions for fitting environmental
variables onto ordination:
\begin{itemize}
\item \code{envfit} fits vectors of continuous variables and centroids
  of levels of class variables (defined as \code{factor} in
  \proglang{R}).  The arrow shows the direction of the (increasing)
  gradient, and the length of the arrow is proportional to the
  correlation between the variable and the ordination.
\item \code{ordisurf} (which requires package \pkg{mgcv}) fits
  smooth surfaces for continuous variables onto ordination using
  thinplate splines with cross-validatory selection of smoothness.
\end{itemize}

Function \code{envfit} can be called with a \code{formula}
interface, and it optionally can assess the ``significance'' of the
variables using permutation tests:
\begin{Schunk}
\begin{Sinput}
> ord.fit <- envfit(ord ~ A1 + Management, data=dune.env, perm=999)
> ord.fit
\end{Sinput}
\begin{Soutput}
***VECTORS

     NMDS1   NMDS2     r2 Pr(>r)  
A1 0.99003 0.14087 0.3797  0.015 *
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Permutation: free
Number of permutations: 999

***FACTORS:

Centroids:
               NMDS1   NMDS2
ManagementBF -0.4474 -0.0194
ManagementHF -0.2688 -0.1256
ManagementNM  0.2975  0.5798
ManagementSF  0.1503 -0.4654

Goodness of fit:
               r2 Pr(>r)   
Management 0.4134  0.007 **
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Permutation: free
Number of permutations: 999
\end{Soutput}
\end{Schunk}
The result can be drawn directly or added to an ordination diagram
(Fig. \ref{fig:envfit}):
\begin{Schunk}
\begin{Sinput}
> plot(ord, dis="site")
> plot(ord.fit)
\end{Sinput}
\end{Schunk}

Function \code{ordisurf} directly adds a fitted surface onto
ordination, but it returns the result of the fitted thinplate spline
\code{gam} (Fig. \ref{fig:envfit}):
\begin{Schunk}
\begin{Sinput}
> ordisurf(ord, A1, add=TRUE)
\end{Sinput}
\begin{Soutput}
Family: gaussian 
Link function: identity 

Formula:
y ~ s(x1, x2, k = 10, bs = "tp", fx = FALSE)

Estimated degrees of freedom:
1.62  total = 2.62 

REML score: 41.42675     
\end{Soutput}
\end{Schunk}
\begin{figure}
\includegraphics{intro-vegan-015}
\caption{Fitted vector and smooth surface for the thickness of A1
  horizon (\code{A1}, in cm), and centroids of Management levels.}
\label{fig:envfit}
\end{figure}

\section{Constrained ordination}

\pkg{Vegan} has three methods of constrained ordination:
constrained or ``canonical'' correspondence analysis (function
\code{cca}), redundancy analysis (function \code{rda}) and
distance-based redundancy analysis (function \code{capscale}).  All
these functions can have a conditioning term that is ``partialled
out''.  I only demonstrate \code{cca}, but all functions accept
similar commands and can be used in the same way.

The preferred way is to use \code{formula} interface, where the left
hand side gives the community data frame and the right hand side lists
the constraining variables:
\begin{Schunk}
\begin{Sinput}
> ord <- cca(dune ~ A1 + Management, data=dune.env)
> ord
\end{Sinput}
\begin{Soutput}
Call: cca(formula = dune ~ A1 + Management, data = dune.env)

              Inertia Proportion Rank
Total          2.1153     1.0000     
Constrained    0.7798     0.3686    4
Unconstrained  1.3355     0.6314   15
Inertia is mean squared contingency coefficient 

Eigenvalues for constrained axes:
  CCA1   CCA2   CCA3   CCA4 
0.3187 0.2372 0.1322 0.0917 

Eigenvalues for unconstrained axes:
   CA1    CA2    CA3    CA4    CA5    CA6    CA7    CA8    CA9   CA10 
0.3620 0.2029 0.1527 0.1345 0.1110 0.0800 0.0767 0.0553 0.0444 0.0415 
  CA11   CA12   CA13   CA14   CA15 
0.0317 0.0178 0.0116 0.0087 0.0047 
\end{Soutput}
\end{Schunk}
The results can be plotted with (Fig. \ref{fig:cca}):
\begin{Schunk}
\begin{Sinput}
> plot(ord)
\end{Sinput}
\end{Schunk}
\begin{figure}
\includegraphics{intro-vegan-018}
\caption{Default plot from constrained correspondence analysis.}
\label{fig:cca}
\end{figure}
There are three groups of items: sites, species and centroids (and
biplot arrows) of environmental variables.  All these can be added
individually to an empty plot, and all previously explained tricks of
controlling graphics still apply.

It is not recommended to perform constrained ordination with all
environmental variables you happen to have: adding the number of
constraints means slacker constraint, and you finally end up with
solution similar to unconstrained ordination. In that case it is
better to use unconstrained ordination with environmental fitting.
However, if you really want to do so, it is possible with the
following shortcut in \code{formula}:
\begin{Schunk}
\begin{Sinput}
> cca(dune ~ ., data=dune.env)
\end{Sinput}
\begin{Soutput}
Call: cca(formula = dune ~ A1 + Moisture + Management + Use +
Manure, data = dune.env)

              Inertia Proportion Rank
Total          2.1153     1.0000     
Constrained    1.5032     0.7106   12
Unconstrained  0.6121     0.2894    7
Inertia is mean squared contingency coefficient 
Some constraints were aliased because they were collinear (redundant)

Eigenvalues for constrained axes:
  CCA1   CCA2   CCA3   CCA4   CCA5   CCA6   CCA7   CCA8   CCA9  CCA10 
0.4671 0.3410 0.1761 0.1532 0.0953 0.0703 0.0589 0.0499 0.0318 0.0260 
 CCA11  CCA12 
0.0228 0.0108 

Eigenvalues for unconstrained axes:
    CA1     CA2     CA3     CA4     CA5     CA6     CA7 
0.27237 0.10876 0.08975 0.06305 0.03489 0.02529 0.01798 
\end{Soutput}
\end{Schunk}

\subsection{Significance tests}

\pkg{vegan} provides permutation tests for the significance of
constraints.  The test mimics standard analysis of variance function
(\code{anova}), and the default test analyses all constraints
simultaneously:
\begin{Schunk}
\begin{Sinput}
> anova(ord)
\end{Sinput}
\begin{Soutput}
Permutation test for cca under reduced model
Permutation: free
Number of permutations: 999

Model: cca(formula = dune ~ A1 + Management, data = dune.env)
         Df ChiSquare      F Pr(>F)    
Model     4   0.77978 2.1896  0.001 ***
Residual 15   1.33549                  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
\end{Soutput}
\end{Schunk}
The function actually used was \code{anova.cca}, but you do not need
to give its name in full, because \proglang{R} automatically chooses the
correct \code{anova} variant for the result of constrained
ordination.

It is also possible to analyse terms separately:
\begin{Schunk}
\begin{Sinput}
> anova(ord, by="term", permutations=199)
\end{Sinput}
\begin{Soutput}
Permutation test for cca under reduced model
Terms added sequentially (first to last)
Permutation: free
Number of permutations: 199

Model: cca(formula = dune ~ A1 + Management, data = dune.env)
           Df ChiSquare      F Pr(>F)   
A1          1   0.22476 2.5245  0.015 * 
Management  3   0.55502 2.0780  0.010 **
Residual   15   1.33549                 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
\end{Soutput}
\end{Schunk}
This test is sequential: the terms are analysed
in the order they happen to be in the model. You can also analyse
significances of marginal effects (``Type III effects''):
\begin{Schunk}
\begin{Sinput}
> anova(ord, by="mar", permutations=199)
\end{Sinput}
\begin{Soutput}
Permutation test for cca under reduced model
Marginal effects of terms
Permutation: free
Number of permutations: 199

Model: cca(formula = dune ~ A1 + Management, data = dune.env)
           Df ChiSquare      F Pr(>F)   
A1          1   0.17594 1.9761  0.035 * 
Management  3   0.55502 2.0780  0.005 **
Residual   15   1.33549                 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
\end{Soutput}
\end{Schunk}

Moreover, it is possible to analyse significance of each axis:
\begin{Schunk}
\begin{Sinput}
> anova(ord, by="axis", permutations=499)
\end{Sinput}
\begin{Soutput}
Permutation test for cca under reduced model
Marginal tests for axes
Permutation: free
Number of permutations: 499

Model: cca(formula = dune ~ A1 + Management, data = dune.env)
         Df ChiSquare      F Pr(>F)   
CCA1      1   0.31875 3.5801  0.002 **
CCA2      1   0.23718 2.6640  0.006 **
CCA3      1   0.13217 1.4845  0.102   
CCA4      1   0.09168 1.0297  0.374   
Residual 15   1.33549                 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
\end{Soutput}
\end{Schunk}

\subsection{Conditioned or partial ordination}

All constrained ordination methods can have terms that are partialled
out from the analysis before constraints:
\begin{Schunk}
\begin{Sinput}
> ord <- cca(dune ~ A1 + Management + Condition(Moisture), data=dune.env)
> ord
\end{Sinput}
\begin{Soutput}
Call: cca(formula = dune ~ A1 + Management +
Condition(Moisture), data = dune.env)

              Inertia Proportion Rank
Total          2.1153     1.0000     
Conditional    0.6283     0.2970    3
Constrained    0.5109     0.2415    4
Unconstrained  0.9761     0.4615   12
Inertia is mean squared contingency coefficient 

Eigenvalues for constrained axes:
   CCA1    CCA2    CCA3    CCA4 
0.24932 0.12090 0.08160 0.05904 

Eigenvalues for unconstrained axes:
    CA1     CA2     CA3     CA4     CA5     CA6     CA7     CA8     CA9 
0.30637 0.13191 0.11516 0.10947 0.07724 0.07575 0.04871 0.03758 0.03106 
   CA10    CA11    CA12 
0.02102 0.01254 0.00928 
\end{Soutput}
\end{Schunk}
This partials out the effect of \code{Moisture} before analysing the
effects of \code{A1} and \code{Management}.  This also influences
the significances of the terms:
\begin{Schunk}
\begin{Sinput}
> anova(ord, by="term", permutations=499)
\end{Sinput}
\begin{Soutput}
Permutation test for cca under reduced model
Terms added sequentially (first to last)
Permutation: free
Number of permutations: 499

Model: cca(formula = dune ~ A1 + Management + Condition(Moisture), data = dune.env)
           Df ChiSquare      F Pr(>F)   
A1          1   0.11543 1.4190   0.13   
Management  3   0.39543 1.6205   0.01 **
Residual   12   0.97610                 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
\end{Soutput}
\end{Schunk}
If we had a designed experiment, we may wish to restrict the
permutations so that the observations only are permuted within levels
of \code{Moisture}. Restricted permutation is based on the powerful
\pkg{permute} package. Function \code{how()} can be used to define
permutation schemes. In the following, we set the levels with
\code{plots} argument:
\begin{Schunk}
\begin{Sinput}
> how <- how(nperm=499, plots = Plots(strata=dune.env$Moisture))
> anova(ord, by="term", permutations = how)
\end{Sinput}
\begin{Soutput}
Permutation test for cca under reduced model
Terms added sequentially (first to last)
Plots: dune.env$Moisture, plot permutation: none
Permutation: free
Number of permutations: 499

Model: cca(formula = dune ~ A1 + Management + Condition(Moisture), data = dune.env)
           Df ChiSquare      F Pr(>F)   
A1          1   0.11543 1.4190  0.262   
Management  3   0.39543 1.6205  0.004 **
Residual   12   0.97610                 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
\end{Soutput}
\end{Schunk}

%%%%%%%%%%%%%%%%%%%

\end{document}
