Written and maintained by CASRAI Editorial Board
Published
On this page
The vegan R package is a free CRAN package for community ecology. Its CRAN description is “Ordination methods, diversity analysis and other functions for community and vegetation ecologists.” This guide covers what it is used for, how to install it, and a worked run on the package’s own dune data: diversity indices, a dissimilarity matrix, non-metric multidimensional scaling (NMDS), a PERMANOVA test and a fit of environmental variables. It is about the ecology package, not the diet, so every function below is documented in the package’s reference pages.
What the vegan R package is used for in research
vegan works on a community matrix: one row per sample or site, one column per species (or taxon), cells holding counts, cover classes or abundances. CRAN lists version 2.7-6 (published 2026-08-31) and requires R 4.1.0 or later, with the permute package as a dependency. The maintainer is Jari Oksanen; the author list includes Gavin L. Simpson, F. Guillaume Blanchet, Roeland Kindt and Pierre Legendre. It is licensed GPL-2 and is free to use.
The package covers four recurring jobs in ecological analysis:
- Diversity within a sample.
diversity()returns Shannon, Simpson or inverse Simpson indices,specnumber()counts species, andrarefy()gives expected richness in a random subsample. For background on the indices see the CASRAI guides on the Shannon diversity index, the Simpson diversity index and species evenness. - Dissimilarity between samples.
vegdist()computes dissimilarity indices such as Bray-Curtis (see the Bray-Curtis guide), Jaccard and Gower. - Ordination.
metaMDS()for NMDS, plus constrained methods such asrda()andcca(). - Testing and interpretation.
adonis2()for permutational multivariate analysis of variance andenvfit()for fitting environmental variables onto an ordination.
The package’s own vignettes (introduction to ordination, partition of variation, diversity analysis, design decisions and a FAQ) are linked from the development site at vegandevs.github.io/vegan.
Install or access the vegan package (official sources only)
The standard route is CRAN, from an R session:
install.packages("vegan")
library(vegan)
The development site gives two other routes. A binary build from R-universe:
install.packages('vegan', repos = c('https://vegandevs.r-universe.dev', 'https://cloud.r-project.org'))
Or the development version from GitHub, which needs the remotes package:
install.packages("remotes")
remotes::install_github("vegandevs/vegan")
The development site currently shows version 2.8-0, ahead of the CRAN release, so results and argument lists can differ between the two. For a paper, install one version, record it with packageVersion("vegan"), and cite the package with citation("vegan"); the project also keeps a “Citing vegan” page.
Step-by-step: diversity, distance, NMDS and PERMANOVA on the dune data
The package ships with dune, cover-class values for 30 plant species at 20 sites in Dutch dune meadows (from Jongman, ter Braak and van Tongeren, 1987), and dune.env, five environmental variables for the same sites: A1 (thickness of the A1 soil horizon), Moisture, Management (BF biological farming, HF hobby farming, NM nature conservation management, SF standard farming), Use and Manure. Running the steps on a bundled dataset lets you check your install before you apply the same calls to your own matrix.
1. Load the package and data
library(vegan)
data(dune)
data(dune.env)
2. Calculate diversity per site
H = diversity(dune, index = "shannon")
D = diversity(dune, index = "simpson")
S = specnumber(dune)
diversity() has the signature diversity(x, index = "shannon", groups, equalize.groups = FALSE, MARGIN = 1, base = exp(1)). For the Shannon index H’ = -sum(pi logb pi), the default base is e. The "simpson" option returns 1 – D and "invsimpson" returns 1/D, where D = sum(pi2). If you pass groups, the function returns pooled (gamma) diversity for each group, and the difference or ratio between that and mean site diversity is a way of expressing beta diversity.
3. Compute a dissimilarity matrix
d = vegdist(dune, method = "bray")
The distance-choice table in the next section lists the documented properties of each index family.
4. Run NMDS with metaMDS
nmds = metaMDS(dune, distance = "bray", k = 2, trymax = 20)
nmds
The default call is metaMDS(comm, distance = "bray", k = 2, try = 20, trymax = 20, engine = monoMDS, autotransform = TRUE, noshare = FALSE, wascores = TRUE, ...). The documentation describes what the wrapper does in order: it transforms the data when values are larger than common abundance class scales, computes dissimilarities, optionally adds step-across dissimilarities when sites share no species, runs NMDS from several random starts to look for a stable solution, scales and rotates the result, and adds species scores as weighted averages.
5. Plot sites and species
plot(nmds, display = "sites", type = "t")
plot(nmds, display = "species", type = "t")
scores(nmds, display = "sites")
6. Test a grouping with adonis2
adonis2(dune ~ Management, data = dune.env, permutations = 999, method = "bray")
The signature is adonis2(formula, data, permutations = 999, method = "bray", sqrt.dist = FALSE, add = FALSE, by = NULL, ...). The left side of the formula is a community matrix or a dissimilarity matrix, the right side holds the explanatory variables, and the rows of data must be in the same order as the community matrix. With by = NULL the overall model is tested; by = "terms" tests each term sequentially and by = "margin" tests marginal effects.
7. Fit environmental variables onto the ordination
ef = envfit(nmds, dune.env, permutations = 999)
ef
plot(nmds, display = "sites")
plot(ef)
envfit() accepts mixed continuous and factor variables. For continuous variables it fits a vector (a linear trend surface); for factors it reports the averages of factor levels. Each variable is analysed separately, with a permutation test.
Choosing a distance index with vegdist
The vegdist() reference page groups its indices by the property its authors document. The table below restates those groupings; it does not rank the indices for your data.
| Indices | Documented property in the vegdist help page |
|---|---|
| Gower, Bray-Curtis, Jaccard, Kulczynski | Good at detecting underlying ecological gradients (Faith et al. 1987) |
| Morisita, Horn-Morisita, Binomial, Cao, Chao | Should be able to handle different sample sizes |
| Mountford, Raup-Crick | For presence-absence data; should handle unknown and variable sample sizes |
| Aitchison | Equivalent to Euclidean distance between centred log-ratio (CLR) transformed samples; for positive compositional data |
| Robust Aitchison (“rlcr”, Martino et al. 2019) | Uses a robust CLR, so it applies to non-negative data that include zeros |
If your preferred index is missing, designdist() lets you define one. The metaMDS() help adds that Bray-Curtis is its default because it often is “the test winner”, and that rankindex() can find the best-performing index for your own data and gradients.
Output and how to read it
Diversity output. diversity() and specnumber() return one value per row, named by your row names. Compare them site by site or aggregate by the grouping variables in dune.env.
NMDS output. Printing the metaMDS object summarises the run, including its stress. Stress is the quantity the random-start search tries to reduce: a new solution replaces the standard only if it has lower stress. In the plot, sites that lie close together have more similar species composition under the chosen index; distances along axes are not absolute because NMDS has no fixed orientation, which is why metaMDS centres and rotates the result to principal axes. With half-change scaling, one unit on an axis corresponds to halving of community similarity from replicate similarity.
Species scores. These are weighted averages of site scores, so a species plots near the sites where it is most abundant. scores(nmds, display = "species") extracts them.
adonis2 output. The table partitions the sums of squares among model terms and gives a pseudo-F and a permutation p-value. A significant result can reflect differences in within-group dispersion as well as differences in group centres, per the help page, which notes that betadisper() is the sister function for studying dispersion. permustat = "modified-F" is available when groups may have unequal dispersion, with the limits documented on the help page (factors only, no Condition terms, no by tests).
envfit output. Each variable is tested separately with a permutation test (999 permutations by default). Calling plot(ef) adds the fitted vectors as arrows to the existing ordination plot, and factors appear at the averages of their levels.
Troubleshooting
- “Result could not be repeated” message from metaMDS. The documentation says the result is still at least as good as starting from metric scaling, and you may not need to do anything. To search harder, raise
trymax; if the maximum number of iterations is reached, increasemaxit, which is passed tomonoMDS. - Too few sites. For
kdimensions the number of points should exceed 2k + 1, and preferably be much higher. - Data that are not community data.
autotransformis intended for community data; for other data types setautotransform = FALSEand choose the distance yourself. - Many sites with no shared species. Consider the
noshareargument, which triggers step-across dissimilarities; the help page notes the default enginemonoMDScan usually handle ties at the maximum dissimilarity. - rarefy() complaints. Rarefaction works only on genuine counts of individuals. A subsample size larger than the community returns the non-rarefied richness with a warning. The help page also cautions that random rarefaction with
rrarefy()discards valid data and suggests normalising transformations throughdecostand()instead. - adonis2 errors on missing values. Missing values are not allowed on the left side, and the default
na.action = na.failstops on missing values on the right side. Remove or handle them first and keep rows aligned. - Version differences. If an example from the development site fails on a CRAN install, compare
packageVersion("vegan")with the version shown at the top of the reference page.
Free alternatives and other routes
| Need | Option | Note |
|---|---|---|
| Rarefaction and extrapolation on Hill numbers | iNEXT | See the CASRAI guide to iNEXT for biodiversity rarefaction; vegan’s own rarefy() and rarecurve() cover rarefaction of counts only. |
| Newer functions before a CRAN release | Development version | Installed from GitHub or R-universe as shown above; version 2.8-0 at the time of reading. |
| A dissimilarity vegan does not list | designdist() inside vegan |
Defines custom indices without leaving the package. |
FAQ
What is the vegan R package?
It is a CRAN package titled “vegan: Community Ecology Package”, providing ordination methods, diversity analysis and related functions for community and vegetation ecologists.
Is the vegan R package free?
Yes. It is released under the GPL-2 licence and installs from CRAN with install.packages("vegan").
Which R version does vegan need?
CRAN lists R 4.1.0 or later for version 2.7-6, with permute 0.9-0 or later as a dependency, and imports MASS, cluster, lattice and mgcv.
How do I cite vegan?
Run citation("vegan") in R and report the version from packageVersion("vegan"). The project also maintains a “Citing vegan” page.
Can vegan be used outside ecology?
The metaMDS documentation says its defaults suit community data and that for other data you should probably select the distance yourself and set autotransform = FALSE.
Sources
Data: vegan R package: core functions, the research question each answers and their documented signatures
Compiled from the vegan reference pages on the package development site: for six core functions, the ecological question it answers and the default signature as documented in version 2.8-0 of the reference.
Period covered: 2026.
| Function | Question it answers | Documented signature (defaults) | Reference page |
|---|---|---|---|
| diversity() | How diverse is each site? | diversity(x, index = "shannon", groups, equalize.groups = FALSE, MARGIN = 1, base = exp(1)) | https://vegandevs.github.io/vegan/reference/diversity.html |
| specnumber() | How many species per site or group? | specnumber(x, groups, MARGIN = 1) | https://vegandevs.github.io/vegan/reference/diversity.html |
| rarefy() | What richness is expected in a random subsample of counts? | rarefy(x, sample, se = FALSE, MARGIN = 1) | https://vegandevs.github.io/vegan/reference/rarefy.html |
| metaMDS() | Which sites have similar composition (NMDS)? | metaMDS(comm, distance = "bray", k = 2, try = 20, trymax = 20, engine = monoMDS, autotransform = TRUE, noshare = FALSE, wascores = TRUE, ...) | https://vegandevs.github.io/vegan/reference/metaMDS.html |
| adonis2() | Does composition differ among groups or along predictors (PERMANOVA)? | adonis2(formula, data, permutations = 999, method = "bray", sqrt.dist = FALSE, add = FALSE, by = NULL, ...) | https://vegandevs.github.io/vegan/reference/adonis.html |
| envfit() | Which environmental variables align with the ordination? | envfit(ord, env, permutations = 999, strata = NULL, choices = c(1,2), display = "sites", w, na.rm = FALSE, ...) | https://vegandevs.github.io/vegan/reference/envfit.html |
Sources
- vegan reference index (vegandevs.github.io) (accessed 2026-11-14)
- vegan: Community Ecology Package (CRAN) (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







