| Title: | Data Handling and Analysis in Macroecology |
|---|---|
| Description: | Handling, processing, and analyzing geographic data on species' distributions and environmental variables. Read Vilela & Villalobos (2015) <doi:10.1111/2041-210X.12401> for details. |
| Authors: | Bruno Vilela [aut, cre] (ORCID: <https://orcid.org/0000-0003-4072-0558>), Fabricio Villalobos [aut] (ORCID: <https://orcid.org/0000-0002-5230-2217>) |
| Maintainer: | Bruno Vilela <[email protected]> |
| License: | GPL-2 |
| Version: | 6.1 |
| Built: | 2026-05-12 17:48:00 UTC |
| Source: | https://github.com/macroecology/letsr |
The letsR package is being developed to help researchers in the handling, processing, and analysis of macroecological data. Its purpose is to integrate these methodological processes into a single software platform for macroecological analyses. The package's main functions allow users to build presence-absence matrices, the basic analytical tool in macroecology, from species' geographical distributions and merge them with species' traits, conservation information (downloadable using functions from this package) and spatial environmental layers. In addition, other package's functions enable users to summarize and visualize information from presence-absence matrices.
All functions in this package use a prefix and a suffix separated by a dot.
The prefix refers to the package's name and the suffix to the actual function.
This is done to avoid confusion with potentially similarly-named functions from other R packages.
For instance, the letsR function used to create presence-absence matrices is called lets.presab (but see also
lets.presab.birds and lets.presab.points) whereas the one used to add variables to a
presence-absence matrix is called lets.addvar.
The package's basic functions create and work on a particular S3 object class called PresenceAbsence.
Such PresenceAbsence object class allows storing information beyond presence-absence data
(e.g. user-defined grid-cell system) and using the generic plot, summary and print functions of R.
Also, some package's functions allow the user to input customary R objects (e.g. vector, matrix,
data.frame).
If you are looking for the most recent version of the package, you can get the development version of letsR on github (https://github.com/macroecology/letsR).
| Package: | lestR |
| Type: | Package |
| Version: | 3.1 |
| Date: | 2018-01-24 |
| License: | GPL-2 |
Bruno Vilela
(email: [email protected];
Website: https://bvilela.weebly.com/)
Fabricio Villalobos
(email: [email protected];
Website: https://fabro.github.io)
Vilela, B., & Villalobos, F. (2015). letsR: a new R package for data handling and analysis in macroecology. Methods in Ecology and Evolution.
Result of the function lets.iucn (deprecated) applied to South American frog genus Phyllomedusa in 2014.
IUCNIUCN
A data frame with 32 rows and 7 columns:
Scientific name
Family
Red List Status
Criteria for listing as threatened
Population trend per IUCN
Year described
Presence in country
IUCN - https://www.iucnredlist.org/. 2014.
Add polygon coverage within cells of a PresenceAbsence object.
lets.addpoly(x, y, z, onlyvar = FALSE, count = FALSE)lets.addpoly(x, y, z, onlyvar = FALSE, count = FALSE)
x |
A |
y |
Polygon of interest. |
z |
A character indicating the column name of the polygon containing the attributes to be used. |
onlyvar |
If |
count |
Logical, if |
The result is a presence-absence matrix of species with the polygons' attributes used added as columns at the right-end of the matrix. The Values represent the percentage of the cell covered by the polygon attribute used.
Bruno Vilela
## Not run: data(PAM) # Phyllomedusa presence-absence matrix data(wrld_simpl) # World map Brazil <- wrld_simpl[wrld_simpl$NAME == "Brazil", ] # Brazil (polygon) # Check where is the variable name # (in this case it is in "NAME" which will be my z value) names(Brazil) PAM_pol <- lets.addpoly(PAM, Brazil, "NAME", onlyvar = TRUE) ## End(Not run)## Not run: data(PAM) # Phyllomedusa presence-absence matrix data(wrld_simpl) # World map Brazil <- wrld_simpl[wrld_simpl$NAME == "Brazil", ] # Brazil (polygon) # Check where is the variable name # (in this case it is in "NAME" which will be my z value) names(Brazil) PAM_pol <- lets.addpoly(PAM, Brazil, "NAME", onlyvar = TRUE) ## End(Not run)
Add variables (in raster format), usually environmental, to a PresenceAbsence object. Variables are included as additional columns containing the aggregate/summarize value of the variable(s) in each cell of the presence-absence matrix.
lets.addvar(x, y, onlyvar = FALSE, fun = mean)lets.addvar(x, y, onlyvar = FALSE, fun = mean)
x |
A |
y |
Variables to be added in |
onlyvar |
If |
fun |
Function used to aggregate the variables(s) values over each cell. Note that this will only work for variables with a resolution value smaller (i.e. higher resolution) than the PAM. |
The result is a presence-absence matrix of species with the variables added as columns at the right-end of the matrix (but see the 'onlyvar' argument).
The PresenceAbsence and the Raster
variable must be in the same projection.
Bruno Vilela
## Not run: data(temp) # Global mean temperature temp <- terra::unwrap(temp) data(PAM) # Phyllomedusa presence-absence matrix # Mean temperature PAM_temp_mean <- lets.addvar(PAM, temp) # Standard deviation of temperature PAM_temp_sd <- lets.addvar(PAM, temp, fun = sd, onlyvar = TRUE) # Mean and SD in the PAM PAM_temp_mean_sd <- cbind(PAM_temp_mean, PAM_temp_sd) ## End(Not run)## Not run: data(temp) # Global mean temperature temp <- terra::unwrap(temp) data(PAM) # Phyllomedusa presence-absence matrix # Mean temperature PAM_temp_mean <- lets.addvar(PAM, temp) # Standard deviation of temperature PAM_temp_sd <- lets.addvar(PAM, temp, fun = sd, onlyvar = TRUE) # Mean and SD in the PAM PAM_temp_mean_sd <- cbind(PAM_temp_mean, PAM_temp_sd) ## End(Not run)
Computes a suite of descriptor variables for each cell of an
attribute-space presence–absence matrix, as returned by
lets.attrpam. Attribute variables are treated as a
two-dimensional space, and the function
derives metrics that characterize: (i) the position of each attribute
cell relative to the attribute-space centroid (mean and
frequency-weighted distances), (ii) its proximity to attribute-space
borders (zero-richness frontier, quantified via multiple distance-based
proxies), and (iii) its isolation within attribute space
(frequency-weighted Euclidean distance to other cells).
When a geographic presence–absence matrix is supplied, the function also links each attribute cell to the geographic cells occupied by the taxa occurring in that cell, allowing the calculation of: (iv) frequency in geographic space, (v) total geographic area, and (vi) geographic isolation statistics (summaries of pairwise distances among associated geographic cells).
lets.attrcells(x, y = NULL, perc = 0.1, remove.cells = FALSE)lets.attrcells(x, y = NULL, perc = 0.1, remove.cells = FALSE)
x |
A list produced by
|
y |
A geographic presence–absence object produced by
|
perc |
Numeric value in the interval 0 to 1 indicating the
proportion of the shortest distances to empty attribute cells to be
averaged in the robust border-distance metric. Default is
|
remove.cells |
Logical. If |
Summarize metrics of the attribute-space PAM
The two attribute variables are standardized to zero mean and unit variance before distance-based calculations.
If y is provided, the function first identifies the taxa present
in each attribute cell, then retrieves the geographic cells occupied by
those taxa in the geographic PAM. Based on these linked geographic
cells, the function computes:
Frequency: number of associated geographic cells;
Area: total area of the associated geographic cells;
summary statistics of pairwise geographic distances among those cells.
If y = NULL, geographic descriptors are not computed. In this
case, attribute-cell richness is used as the weighting variable in the
midpoint and frequency-weighted distance calculations.
Empty attribute cells are defined as cells with zero frequency when
y is provided, or zero richness when y = NULL. Cells with
NA values in the richness raster are treated as empty.
Distances to the weighted and unweighted midpoints are returned as negative values so that larger values indicate greater centrality in attribute space.
A data.frame with one row per attribute cell. The output always
contains:
Cell_attr: attribute-cell identifier.
Weighted Mean Distance to midpoint: negative Euclidean
distance from the cell to the weighted midpoint of occupied attribute
space.
Mean Distance to midpoint: negative Euclidean distance
from the cell to the unweighted midpoint of occupied attribute space.
Minimum Zero Distance: minimum distance from the cell to
any empty attribute cell.
Minimum X% Zero Distance: mean distance from the cell to
the nearest fraction of empty attribute cells defined by
perc, where X = perc * 100.
Distance to MCP border: distance from the cell to the
border of the minimum convex polygon enclosing occupied attribute
cells.
Frequency Weighted Distance: weighted mean distance from
the cell to all other attribute cells.
When y is provided, the output additionally includes:
Frequency: number of geographic cells associated with the
taxa present in the attribute cell.
Area: summed area of those associated geographic cells.
Isolation (Min.), Isolation (1st Qu.),
Isolation (Median), Isolation (Mean),
Isolation (3rd Qu.), and Isolation (Max.): summary
statistics of pairwise geographic distances among associated
geographic cells.
## Not run: # Example using a geographic PAM and simulated attribute data data("PAM") n <- length(PAM$Species_name) Species <- PAM$Species_name trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) df <- data.frame(Species, trait_a, trait_b) # Build the attribute-space PAM x <- lets.attrpam(df, n_bins = 4) # Calculate attribute-cell descriptors using the geographic PAM cell_desc <- lets.attrcells(x, y = PAM) # Plot the resulting descriptors lets.plot.attrcells(x, cell_desc) ## End(Not run)## Not run: # Example using a geographic PAM and simulated attribute data data("PAM") n <- length(PAM$Species_name) Species <- PAM$Species_name trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) df <- data.frame(Species, trait_a, trait_b) # Build the attribute-space PAM x <- lets.attrpam(df, n_bins = 4) # Calculate attribute-cell descriptors using the geographic PAM cell_desc <- lets.attrcells(x, y = PAM) # Plot the resulting descriptors lets.plot.attrcells(x, cell_desc) ## End(Not run)
Builds a presence–absence matrix (PAM) in a two-dimensional trait space, by binning species occurrences along two quantitative attributes (e.g., body size and mass). Each species can have one or multiple entries in the trait dataset.
lets.attrpam( x, n_bins = 10, remove.cells = TRUE, remove.sp = TRUE, count = FALSE )lets.attrpam( x, n_bins = 10, remove.cells = TRUE, remove.sp = TRUE, count = FALSE )
x |
A data frame where the first column contains species (character vector), and the next two columns contain numeric trait values (2D space). |
n_bins |
Integer. Number of bins per axis (default = 10). |
remove.cells |
Logical. Should cells with no species be removed from the final matrix? |
remove.sp |
Logical. Should species with no occurrences in attribute space be removed? |
count |
Logical. If 'TRUE', displays a progress bar for species processing. |
Create a Presence–Absence Matrix in Trait Space
The two trait axes are divided into equal-interval bins, generating a grid of 'n_bins × n_bins' cells. Each species occurrence is assigned to a cell, and the resulting PAM indicates which species are present in each trait cell.
A list with two components:
PAM_attribute: a matrix with cell ID, trait coordinates, and species presence (0/1).
Attr_Richness_Raster: a raster of richness (number of species) in trait space.
## Not run: n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * .2 + rnorm(n) x <- data.frame(Species, trait_a, trait_b) pam_att <- lets.attrpam(x, n_bins = 30) lets.plot.attrpam(pam_att) ## End(Not run)## Not run: n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * .2 + rnorm(n) x <- data.frame(Species, trait_a, trait_b) pam_att <- lets.attrpam(x, n_bins = 30) lets.plot.attrpam(pam_att) ## End(Not run)
Based on a species Presence-Absence matrix including
variables of interest (see lets.addvar), the
function divides a continuous variable into classes and counts
the frequency of each class within each species' range.
lets.classvar(x, groups = "default", pos, xy)lets.classvar(x, groups = "default", pos, xy)
x |
Presence-absence |
groups |
The number of classes into which the variable will be divided.
Default calculates the number of classes as the
default for a histogram ( |
pos |
Column number containing the variable of interest. |
xy |
Logical, if |
A matrix with species in the rows and the variable's
classes in the columns.
Bruno Vilela
Morales-Castilla et al. 2013. Range size patterns of New World oscine passerines (Aves): insights from differences among migratory and sedentary clades. Journal of Biogeography, 40, 2261-2273.
## Not run: data(PAM) data(temp) pamvar <- lets.addvar(PAM, temp) resu <- lets.classvar(x = pamvar, pos = ncol(pamvar), xy = TRUE) ## End(Not run)## Not run: data(PAM) data(temp) pamvar <- lets.addvar(PAM, temp) resu <- lets.classvar(x = pamvar, pos = ncol(pamvar), xy = TRUE) ## End(Not run)
Computes the Moran's I correlogram of a single or multiple variables.
lets.correl(x, y, z, equidistant = FALSE, plot = TRUE)lets.correl(x, y, z, equidistant = FALSE, plot = TRUE)
x |
A single numeric variable in vector format or multiple variables in matrix format (as columns). |
y |
A distance matrix of class |
z |
The number of distance classes to use in the correlogram. |
equidistant |
Logical, if |
plot |
Logical, if |
Returns a matrix with the Moran's I Observed value, Confidence Interval (95 and Expected value. Also the p value of the randomization test, the mean distance between classes, and the number of observations. quase tudo
Bruno Vilela, Fabricio Villalobos, Lucas Jardim & Jose Alexandre Diniz-Filho
Sokal, R.R. & Oden, N.L. (1978) Spatial autocorrelation in biology. 1. Methodology. Biological Journal of the Linnean Society, 10, 199-228.
Sokal, R.R. & Oden, N.L. (1978) Spatial autocorrelation in biology. 2. Some biological implications and four applications of evolutionary and ecological interest. Biological Journal of the Linnean Society, 10, 229-249.
## Not run: data(PAM) data(IUCN) # Spatial autocorrelation in description year (species level) midpoint <- lets.midpoint(PAM) distan <- lets.distmat(midpoint[, 2:3]) moran <- lets.correl(IUCN$Description, distan, 12, equidistant = FALSE, plot = TRUE) ## End(Not run)## Not run: data(PAM) data(IUCN) # Spatial autocorrelation in description year (species level) midpoint <- lets.midpoint(PAM) distan <- lets.distmat(midpoint[, 2:3]) moran <- lets.correl(IUCN$Description, distan, 12, equidistant = FALSE, plot = TRUE) ## End(Not run)
Calculates a geographic distance matrix based on a
PresenceAbsence or a two column matrix of x(longitude) and
y(latitude).
lets.distmat(xy, asdist = TRUE)lets.distmat(xy, asdist = TRUE)
xy |
A |
asdist |
Logical, if |
This function basically facilitates the use of
terra::distance on a PresenceAbsence object, allowing also
the user to have directly a dist object. The distance is always
expressed in meter if the coordinate reference system is
longitude/latitude, and in map units otherwise. Map units are typically
meter, but inspect crs(x) if in doubt.
The user can choose between dist and matrix class
object to be returned. The resulting values are in kilometres (but see the
argument 'unit' in rdist.earth).
Bruno Vilela & Fabricio Villalobos
## Not run: data(PAM) distPAM <- lets.distmat(PAM) ## End(Not run)## Not run: data(PAM) distPAM <- lets.distmat(PAM) ## End(Not run)
Computes a suite of descriptors for each environmental cell in an environmental presence–absence matrix (envPAM), including: (i) frequency in geographic space, (ii) geographic isolation statistics (summary of pairwise distances among geographic cells mapped to the same environmental cell), (iii) distance to environmental midpoints (mean and frequency-weighted mean), (iv) distance to environmental “border” (zero-richness frontier via three proxies), and (v) an environmental isolation metric based on frequency-weighted Euclidean distance in standardized environmental space.
Distances to midpoints are returned inverted (i.e., larger values imply greater centrality in environmental space), following the current implementation.
lets.envcells(x, perc = 0.2, remove.cells = FALSE)lets.envcells(x, perc = 0.2, remove.cells = FALSE)
x |
A list returned by
|
perc |
Numeric in (0,1], the fraction used in the robust border metric (mean of the n smallest distances to zero-richness cells). Default = 0.1. |
remove.cells |
Logical. If 'TRUE', remove empty cells from the results. |
Summarize environmental–geographical metrics from an environmental space PAM
Environmental variables (assumed to be the 2nd and 3rd columns of
$Presence_and_Absence_Matrix_env) are z-scored before computing distances.
Geographic isolation is summarized with summary() of pairwise distances
among geographic cells that collapse to the same environmental cell.
A data frame with one row per environmental cell. The output includes:
Cell_env: Environmental cell identifier.
Frequency: Number of geographic cells mapped to the environmental cell.
Area: Summed area of the associated geographic cells.
Isolation (Min.), Isolation (1st Qu.), Isolation (Median),
Isolation (Mean), Isolation (3rd Qu.), and Isolation (Max.):
Summary statistics of pairwise geographic distances among associated geographic cells.
Weighted Mean Distance to midpoint: Negated distance from the cell to the
frequency-weighted midpoint in standardized environmental space.
Mean Distance to midpoint: Negated distance from the cell to the unweighted
midpoint in standardized environmental space.
Minimum Zero Distance: Minimum distance from the cell to any empty environmental cell.
A column named according to perc (e.g., Minimum 10% Zero Distance):
Mean distance from the cell to the nearest fraction of empty environmental cells.
Distance to MCP border: Distance from the cell to the environmental-space border.
Frequency Weighted Distance: Frequency-weighted mean distance from the cell
to all other environmental cells.
(1) The code assumes the first column of $Presence_and_Absence_Matrix_env
indexes environmental cells and columns 2–3 are the two environmental variables.
(2) The geographic matrix assumes lon/lat at columns 3–4. Adjust indices if needed.
(3) If there are no zero-richness cells or < 3 occupied env cells, border metrics
are returned as NA.
lets.envpam, lets.plot.envcells, lets.plot.envpam
## Not run: data("Phyllomedusa"); data("prec"); data("temp") prec <- unwrap(prec); temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, terra::vect(wrld_simpl)) res <- lets.envpam(PAM, envs, n_bins = 30) out <- lets.envcells(res, perc = 0.2) lets.plot.envcells(res, out) ## End(Not run)## Not run: data("Phyllomedusa"); data("prec"); data("temp") prec <- unwrap(prec); temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, terra::vect(wrld_simpl)) res <- lets.envpam(PAM, envs, n_bins = 30) out <- lets.envcells(res, perc = 0.2) lets.plot.envcells(res, out) ## End(Not run)
Transform a presence–absence matrix (PAM) based on geographic coordinates into a new PAM structured in environmental space. The function rasterizes the environmental variable space (based on two continuous environmental predictors), and assigns species presences to binned environmental conditions, producing a species richness raster in environmental space.
lets.envpam( pam, envs, n_bins = 30, remove.cells = TRUE, remove.sp = TRUE, count = FALSE )lets.envpam( pam, envs, n_bins = 30, remove.cells = TRUE, remove.sp = TRUE, count = FALSE )
pam |
A 'PresenceAbsence' object, typically created using
|
envs |
A two-column matrix or data frame with continuous environmental variables corresponding to the coordinates in the PAM. The first column will be used as the x-axis and the second as the y-axis in the environmental space. |
n_bins |
Number of bins used to discretize each environmental variable. Default is 30. |
remove.cells |
Logical. Should cells with no species be removed from the final matrix? |
remove.sp |
Logical. Should species with no occurrences in environmental space be removed? |
count |
Logical. If TRUE, displays a progress bar for species processing. |
This function projects species occurrences into a two-dimensional
environmental space, facilitating ecological analyses that depend on
environmental gradients. The environmental space is discretized into a
regular grid (determined by n_bins), and each cell is assigned the
number of species occurring under those environmental conditions.
A list with the following elements:
Presence_and_Absence_Matrix_env: A matrix of species presences across environmental bins.
Presence_and_Absence_Matrix_geo: The original PAM coordinates associated with environmental cells.
Env_Richness_Raster: A raster layer of species richness in environmental space.
Geo_Richness_Raster: The original species richness raster in geographic space.
Bruno Vilela
lets.presab, lets.addvar,
lets.plot.envpam
## Not run: # Load data data("Phyllomedusa") data("prec") data("temp") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Preciptation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) # Run function res <- lets.envpam(PAM, envs) # Plot results lets.plot.envpam(x = res, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, T, world = TRUE, mar = c(4, 4, 4, 4)) ## End(Not run)## Not run: # Load data data("Phyllomedusa") data("prec") data("temp") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Preciptation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) # Run function res <- lets.envpam(PAM, envs) # Plot results lets.plot.envpam(x = res, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, T, world = TRUE, mar = c(4, 4, 4, 4)) ## End(Not run)
Create single species' values based on the attributes of species co-occurring within individual ranges.
lets.field(x, y, z, weight = TRUE, xy = NULL, count = FALSE)lets.field(x, y, z, weight = TRUE, xy = NULL, count = FALSE)
x |
A |
y |
Species attribute to be considered. It must be a numeric attribute. |
z |
Species names in the same order as the attributes and exactly the
same as named in the |
weight |
If |
xy |
If |
count |
Logical, if |
If the species do not co-occur with any other species NaN will be returned.
Bruno Vilela & Fabricio Villalobos
Villalobos, F. and Arita, H.T. 2010. The diversity field of New World leaf-nosed bats (Phyllostomidae). Global Ecology and Biogeography. 19, 200-211.
Villalobos, F., Rangel, T.F., and Diniz-Filho, J.A.F. 2013. Phylogenetic fields of species: cross-species patterns of phylogenetic structure and geographical coexistence. Proceedings of the Royal Society B. 280, 20122570.
## Not run: data(PAM) range <- lets.rangesize(x = PAM, units = "cell") field <- lets.field(PAM, range, PAM$S, weight = TRUE) ## End(Not run)## Not run: data(PAM) range <- lets.rangesize(x = PAM, units = "cell") field <- lets.field(PAM, range, PAM$S, weight = TRUE) ## End(Not run)
This function creates a grid in shapefile format and adds its cells' IDs to the presence-absence matrix. The function was created to facilitate the use of the PresenceAbsence object for the ones who prefer to work with a grid in shapefile format.
lets.gridirizer(x)lets.gridirizer(x)
x |
A |
The result is a list of two objects. The first is a grid in shapefile format; the second is a presence-absence matrix with an aditional column called SP_ID (shapefile cell identifier).
Bruno Vilela
## Not run: data(PAM) PAM.grid <- lets.gridirizer(PAM) names(PAM.grid) # Grid in polygon format (can be saved in shapefile) PAM.grid$Grid # Presence-absence matrix (beggining only) head(PAM.grid$Presence[, 1:5]) ## End(Not run)## Not run: data(PAM) PAM.grid <- lets.gridirizer(PAM) names(PAM.grid) # Grid in polygon format (can be saved in shapefile) PAM.grid$Grid # Presence-absence matrix (beggining only) head(PAM.grid$Presence[, 1:5]) ## End(Not run)
Transform IUCN RedList conservation status to continuous values ranging from 0 to 5.
lets.iucncont(x, dd = NA, ne = NA)lets.iucncont(x, dd = NA, ne = NA)
x |
A vector or a matrix containing IUCN codes to be transformed. |
dd |
The value to be attributed to DD (data-deficient) species, the default option is NA. |
ne |
The value to be attributed to NE (not-evaluated) species, the default option is NA. |
Returns a vector/matrix with continuos values from 0 to 5.
EX and EW = 5
CR = 4
EN = 3
VU = 2
NT = 1
LC = 0
DD = NA
NE = NA
Bruno Vilela
Purvis A et al., 2000. Predicting extinction risk in declining species. Proceedings of the Royal Society of London. Series B: Biological Sciences, 267.1456: 1947-1952.
## Not run: #Vector transformation status <- sample(c("EN","VU", "NT", "CR", "DD", "LC", "EX"), 30, replace = TRUE) transV <- lets.iucncont(status) #matrix transformation data(IUCN) transM <- lets.iucncont(IUCN) ## End(Not run)## Not run: #Vector transformation status <- sample(c("EN","VU", "NT", "CR", "DD", "LC", "EX"), 30, replace = TRUE) transV <- lets.iucncont(status) #matrix transformation data(IUCN) transM <- lets.iucncont(IUCN) ## End(Not run)
Reload PresenceAbsence objects written with the function
lets.save.
lets.load(file)lets.load(file)
file |
a character string giving the name of the file to load. |
Bruno Vilela
## Not run: data(PAM) lets.save(PAM, file = "PAM.RData") PAM <- lets.load(file = "PAM.RData") ## End(Not run)## Not run: data(PAM) lets.save(PAM, file = "PAM.RData") PAM <- lets.load(file = "PAM.RData") ## End(Not run)
Summarize species atributes per cell in a presence-absence matrix.
lets.maplizer(x, y, z, func = mean, ras = FALSE, weighted = FALSE)lets.maplizer(x, y, z, func = mean, ras = FALSE, weighted = FALSE)
x |
A |
y |
Species attribute to be considered. It must be a numeric attribute. |
z |
Species names in the same order as the attributes and exactly the
same as named in the |
func |
A function to summarize the species' atribute in each cell (the function must return only one value). |
ras |
If |
weighted |
If TRUE, argument func is ignored, and weighted mean is calculated. Weights are attributed to each species according to 1/N cells that the species occur. |
The result can be both a matrix or a list cointaining
the follow objects:
Matrix: a matrix object with the cells' geographic
coordinates and the summarized species' attributes within them.
Raster: The summarized species'attributed maped in a
SpatRaster object.
Bruno Vilela
## Not run: data(PAM) data(IUCN) trait <- IUCN$Description_Year resu <- lets.maplizer(PAM, trait, PAM$S, ras = TRUE) head(resu$Matrix) plot(resu$Raster, xlab = "Longitude", ylab = "Latitude", main = "Mean description year per site") ## End(Not run)## Not run: data(PAM) data(IUCN) trait <- IUCN$Description_Year resu <- lets.maplizer(PAM, trait, PAM$S, ras = TRUE) head(resu$Matrix) plot(resu$Raster, xlab = "Longitude", ylab = "Latitude", main = "Mean description year per site") ## End(Not run)
Summarizes species attributes (e.g., trait values, description year) within
each attribute-space cell of a presence–absence matrix produced by
lets.attrpam. A summary function is applied across
the attributes of species present in each cell, producing a per-cell attribute
surface and an optional raster for visualization.
lets.maplizer.attr(x, y, z, func = mean, ras = TRUE, weighted = FALSE)lets.maplizer.attr(x, y, z, func = mean, ras = TRUE, weighted = FALSE)
x |
An object returned by |
y |
A numeric vector with species attributes to summarize (one value per
species in |
z |
A character vector of species names corresponding to |
func |
A function to summarize attributes across species within each cell
(e.g., |
ras |
Logical; if |
weighted |
If TRUE, argument func is ignored, and weighted mean is calculated. Weights are attributed to each species according to 1/N cells that the species occur. |
Map species attributes in attribute space
Internally, the function multiplies each species presence column by its attribute
value in y (matched by name via z), sets zeros to NA so that
summary functions ignore absences, applies func across species for each cell,
and rasterizes the resulting per-cell summaries onto the attribute raster template.
Cells with no species remain as NA.
A list with:
Matrix_attr: matrix/data.frame with summarized attribute values
per attribute cell (first columns are the cell ID and the two attribute axes).
Attr_Raster: SpatRaster with the summarized attribute
mapped in attribute space.
Bruno Vilela
lets.attrpam, lets.plot.attrpam,
lets.attrcells
## Not run: # Simulate a dataset of 2000 species with two traits n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) df <- data.frame(Species, trait_a, trait_b) # Build attribute-space PAM x <- lets.attrpam(df, n_bins = 30) # Map species-level attribute (here, trait_b) by cell using the mean res <- lets.maplizer.attr(x, y = trait_b, z = Species) # Plot attribute raster lets.plot.attrpam(res) ## End(Not run)## Not run: # Simulate a dataset of 2000 species with two traits n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) df <- data.frame(Species, trait_a, trait_b) # Build attribute-space PAM x <- lets.attrpam(df, n_bins = 30) # Map species-level attribute (here, trait_b) by cell using the mean res <- lets.maplizer.attr(x, y = trait_b, z = Species) # Plot attribute raster lets.plot.attrpam(res) ## End(Not run)
Summarize species-level attributes (e.g., traits or conservation data) within each cell of environmental and geographic presence–absence matrices, enabling trait-based mapping across environmental gradients and geographic space.
lets.maplizer.env(x, y, z, func = mean, ras = TRUE, weighted = FALSE)lets.maplizer.env(x, y, z, func = mean, ras = TRUE, weighted = FALSE)
x |
An object produced by |
y |
A numeric vector containing the species attributes to be summarized (e.g., description year, body size). |
z |
A character vector with species names corresponding to the values in |
func |
A function used to summarize the attribute across species in each cell (e.g., |
ras |
Logical. If |
weighted |
If TRUE, argument func is ignored, and weighted mean is calculated. Weights are attributed to each species according to 1/N cells that the species occur. |
This function is useful for trait-based macroecological analyses that aim to
understand how species attributes vary across environments or space. It uses
the output of lets.envpam, applies a summary function to the
trait values of all species present in each cell, and returns raster layers
for visualization.
A list with the following elements:
Matrix_env: A matrix with summarized attribute values in environmental space.
Matrix_geo: A matrix with summarized attribute values in geographic space.
Env_Raster: A SpatRaster with the attribute values mapped in environmental space.
Geo_Raster: A SpatRaster with the attribute values mapped in geographic space.
Bruno Vilela
lets.envpam, lets.maplizer, lets.plot.envpam
## Not run: # Load data data("Phyllomedusa") data("prec") data("temp") data("IUCN") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Preciptation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) # Create environmental PAM res <- lets.envpam(PAM, envs, remove.cells = FALSE) # Map mean description year res_map <- lets.maplizer.env(res, y = IUCN$Description_Year, z = IUCN$Species) # Plotting trait maps lets.plot.envpam(res_map) ## End(Not run)## Not run: # Load data data("Phyllomedusa") data("prec") data("temp") data("IUCN") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Preciptation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) # Create environmental PAM res <- lets.envpam(PAM, envs, remove.cells = FALSE) # Map mean description year res_map <- lets.maplizer.env(res, y = IUCN$Description_Year, z = IUCN$Species) # Plotting trait maps lets.plot.envpam(res_map) ## End(Not run)
Calculate species distribution midpoint from a presence-absence matrix using several methods.
lets.midpoint(pam, planar = FALSE, method = "PC", inside = FALSE)lets.midpoint(pam, planar = FALSE, method = "PC", inside = FALSE)
pam |
A presence-absence |
planar |
Logical, if |
method |
Default option, "PC" (polygon centroid) will generate a polygon
from the raster, and calculate the centroid of this polygon based on the
function |
inside |
logical. If TRUE the points returned are guaranteed to be inside the polygons or on the lines, but they are not the true centroids. True centroids may be outside a polygon, for example when a polygon is "bean shaped", and they are unlikely to be on their line |
A data.frame containing the species' names and geographic
coordinates (longitude [x], latitude [y]) of species' midpoints.
Fabricio Villalobos & Bruno Vilela
## Not run: data(PAM) mid <- lets.midpoint(PAM, method = "PC") mid2 <- lets.midpoint(PAM, method = "GM") mid3 <- lets.midpoint(PAM, method = "CMD") mid4 <- lets.midpoint(PAM, method = "MCC") mid5 <- lets.midpoint(PAM, method = "PC", planar = TRUE) mid6 <- lets.midpoint(PAM, method = "GM", planar = TRUE) mid7 <- lets.midpoint(PAM, method = "CMD", planar = TRUE) mid8 <- lets.midpoint(PAM, method = "MCC", planar = TRUE) for (sp in seq_len(nrow(mid))) { #sp = 4 # Or choose a line or species plot(PAM, name = mid[sp, 1]) points(mid[sp, -1], col = adjustcolor("blue", .8), pch = 20, cex = 1.5) points(mid2[sp, -1], col = adjustcolor("green", .8), pch = 20, cex = 1.5) points(mid3[sp, -1], col = adjustcolor("yellow", .8), pch = 20, cex = 1.5) points(mid4[sp, -1], col = adjustcolor("purple", .8), pch = 20, cex = 1.5) points(mid5[sp, -1], col = adjustcolor("orange", .8), pch = 20, cex = 1.5) points(mid6[sp, -1], col = adjustcolor("black", .8), pch = 20, cex = 1.5) points(mid7[sp, -1], col = adjustcolor("gray", .8), pch = 20, cex = 1.5) points(mid8[sp, -1], col = adjustcolor("brown", .8), pch = 20, cex = 1.5) Sys.sleep(1) } ## End(Not run)## Not run: data(PAM) mid <- lets.midpoint(PAM, method = "PC") mid2 <- lets.midpoint(PAM, method = "GM") mid3 <- lets.midpoint(PAM, method = "CMD") mid4 <- lets.midpoint(PAM, method = "MCC") mid5 <- lets.midpoint(PAM, method = "PC", planar = TRUE) mid6 <- lets.midpoint(PAM, method = "GM", planar = TRUE) mid7 <- lets.midpoint(PAM, method = "CMD", planar = TRUE) mid8 <- lets.midpoint(PAM, method = "MCC", planar = TRUE) for (sp in seq_len(nrow(mid))) { #sp = 4 # Or choose a line or species plot(PAM, name = mid[sp, 1]) points(mid[sp, -1], col = adjustcolor("blue", .8), pch = 20, cex = 1.5) points(mid2[sp, -1], col = adjustcolor("green", .8), pch = 20, cex = 1.5) points(mid3[sp, -1], col = adjustcolor("yellow", .8), pch = 20, cex = 1.5) points(mid4[sp, -1], col = adjustcolor("purple", .8), pch = 20, cex = 1.5) points(mid5[sp, -1], col = adjustcolor("orange", .8), pch = 20, cex = 1.5) points(mid6[sp, -1], col = adjustcolor("black", .8), pch = 20, cex = 1.5) points(mid7[sp, -1], col = adjustcolor("gray", .8), pch = 20, cex = 1.5) points(mid8[sp, -1], col = adjustcolor("brown", .8), pch = 20, cex = 1.5) Sys.sleep(1) } ## End(Not run)
Creates a species geographic overlap matrix from a Presence-absence matrix.
lets.overlap(pam, method = "Chesser&Zink", xy = NULL)lets.overlap(pam, method = "Chesser&Zink", xy = NULL)
pam |
A presence-absence matrix (sites in rows and species in columns,
with the first two columns containing the longitudinal and latitudinal
coordinates, respectively), or an object of class
|
method |
The method used to calculate the overlap matrix. "Chesser&Zink" calculates the degree of overlap as the proportion of the smaller range that overlaps within the larger range (Chesser & Zink 1994). "Proportional" calculates the proportion of a range that overlaps another range, the resultant matrix is not symmetric. "Cells" will show the number of overlapping grid cells between a pair of species' ranges (same for both species in a pair), here the resultant matrix is symmetric. |
xy |
Logical, if |
Fabricio Villalobos & Bruno Vilela
Chesser, R. Terry, and Robert M. Zink. "Modes of speciation in birds: a test of Lynch's method." Evolution (1994): 490-497.
Barraclough, Timothy G., and Alfried P. Vogler. "Detecting the geographical pattern of speciation from species-level phylogenies." The American Naturalist 155.4 (2000): 419-434.
## Not run: data(PAM) CZ <- lets.overlap(PAM, method = "Chesser&Zink") prop <- lets.overlap(PAM, method = "Proportional") cells <- lets.overlap(PAM, method = "Cells") ## End(Not run)## Not run: data(PAM) CZ <- lets.overlap(PAM, method = "Chesser&Zink") prop <- lets.overlap(PAM, method = "Proportional") cells <- lets.overlap(PAM, method = "Cells") ## End(Not run)
Crop a PresenceAbsence object based on a shapefile provided by the user.
lets.pamcrop(x, shp, remove.sp = TRUE, remove.cells = FALSE)lets.pamcrop(x, shp, remove.sp = TRUE, remove.cells = FALSE)
x |
A |
shp |
Object of class SpatVector (see function
|
remove.sp |
Logical, if |
remove.cells |
Logical, if |
The result is an object of class PresenceAbsence croped.
Bruno Vilela
## Not run: data(PAM) data("wrld_simpl") # PAM before crop plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") # Crop PAM to Brazil data(wrld_simpl) # World map Brazil <- wrld_simpl[wrld_simpl$NAME == "Brazil", ] # Brazil (polygon) PAM_crop <- lets.pamcrop(PAM, Brazil, remove.sp = TRUE) plot(PAM_crop, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness (Brazil crop)") plot(sf::st_geometry(wrld_simpl), add = TRUE) ## End(Not run)## Not run: data(PAM) data("wrld_simpl") # PAM before crop plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") # Crop PAM to Brazil data(wrld_simpl) # World map Brazil <- wrld_simpl[wrld_simpl$NAME == "Brazil", ] # Brazil (polygon) PAM_crop <- lets.pamcrop(PAM, Brazil, remove.sp = TRUE) plot(PAM_crop, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness (Brazil crop)") plot(sf::st_geometry(wrld_simpl), add = TRUE) ## End(Not run)
Maps each descriptor column returned by lets.attrcells back
onto the attribute raster. Optionally returns the rasters without plotting.
lets.plot.attrcells( x, y, ras = FALSE, plot_ras = TRUE, col_func = NULL, mfrow = c(4, 4) )lets.plot.attrcells( x, y, ras = FALSE, plot_ras = TRUE, col_func = NULL, mfrow = c(4, 4) )
x |
A list returned by |
y |
A |
ras |
Logical; if |
plot_ras |
Logical; if |
col_func |
A custom color ramp palette function to use for plotting variables (e.g., from |
mfrow |
A vector of the form c(nr, nc). The figures will be drawn in an nr-by-nc array on the device by rows as in par documentation. |
Plot attribute-cell descriptors as rasters
Rows with zero or NA richness are masked before plotting, to avoid
edge artifacts from empty attribute cells. The plotting grid defaults to
par(mfrow = c(4, 4)); adjust as needed.
If ras = TRUE, returns a named list
of SpatRaster layers (one per descriptor column).
## Not run: # Example with simulated traits data(PAM) n <- length(PAM$Species_name) Species <- PAM$Species_name trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) # correlated trait df <- data.frame(Species, trait_a, trait_b) # Build AttrPAM x <- lets.attrpam(df, n_bins = 4) # Compute descriptors desc <- lets.attrcells(x, PAM) # Plot descriptors lets.plot.attrcells(x, desc) ## End(Not run)## Not run: # Example with simulated traits data(PAM) n <- length(PAM$Species_name) Species <- PAM$Species_name trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) # correlated trait df <- data.frame(Species, trait_a, trait_b) # Build AttrPAM x <- lets.attrpam(df, n_bins = 4) # Compute descriptors desc <- lets.attrcells(x, PAM) # Plot descriptors lets.plot.attrcells(x, desc) ## End(Not run)
Plots the richness (or a single species) in the attribute (trait) space
generated by lets.attrpam.
lets.plot.attrpam(x, species = NULL, cell_id = NULL, col_rich = NULL, ...)lets.plot.attrpam(x, species = NULL, cell_id = NULL, col_rich = NULL, ...)
x |
A list returned by |
species |
Optional. A character string with the name of a species to highlight. If provided, plots its presence in trait space. |
cell_id |
An integer or vector of integers indicating attribute space cell(s) to be highlighted. |
col_rich |
Optional. A color palette function or vector. If 'NULL', a default palette is used (red ramp for species maps, red–white ramp for richness). |
... |
Additional arguments passed to |
Plot an Attribute-space PAM
## Not run: # Example with simulated traits n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) # correlated trait df <- data.frame(Species, trait_a, trait_b) # Build AttrPAM x <- lets.attrpam(df, n_bins = 30) lets.plot.attrpam(x) ## End(Not run)## Not run: # Example with simulated traits n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) # correlated trait df <- data.frame(Species, trait_a, trait_b) # Build AttrPAM x <- lets.attrpam(df, n_bins = 30) lets.plot.attrpam(x) ## End(Not run)
Plots each column of the descriptor table returned by
lets.envcells back onto the environmental richness raster
embedded in the environmental space PAM object.
lets.plot.envcells( x, y, ras = FALSE, plot_ras = TRUE, mfrow = c(4, 4), which.plot = NULL, col_func = NULL, ... )lets.plot.envcells( x, y, ras = FALSE, plot_ras = TRUE, mfrow = c(4, 4), which.plot = NULL, col_func = NULL, ... )
x |
The envPAM list returned by |
y |
A |
ras |
Logical; if |
plot_ras |
Logical; if |
mfrow |
A vector of the form c(nr, nc). The figures will be drawn in an nr-by-nc array on the device by rows as in par documentation. |
which.plot |
Indicate the number of the columns in y to be ploted. |
col_func |
A custom color ramp palette function to use for plotting variables (e.g., from |
... |
other arguments passed to |
Plot environmental descriptors over the environmental raster grid
Each descriptor column is assigned as values of the environmental raster
template and plotted sequentially. Rows with zero frequency are masked as
NA. The plotting grid defaults to par(mfrow = c(4,4)).
If ras = TRUE, returns a named list of SpatRaster
objects corresponding to each descriptor column.
## Not run: data("Phyllomedusa"); data("prec"); data("temp") prec <- unwrap(prec); temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, terra::vect(wrld_simpl)) res <- lets.envpam(PAM, envs, n_bins = 30) out <- lets.envcells(res, perc = 0.2) lets.plot.envcells(res, out) ## End(Not run)## Not run: data("Phyllomedusa"); data("prec"); data("temp") prec <- unwrap(prec); temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, terra::vect(wrld_simpl)) res <- lets.envpam(PAM, envs, n_bins = 30) out <- lets.envcells(res, perc = 0.2) lets.plot.envcells(res, out) ## End(Not run)
This function plots species richness in both environmental and geographical space
based on the output of lets.envpam. It can optionally highlight species
distributions, individual cells, or regions in both spaces.
lets.plot.envpam( x, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, geo_plot = TRUE, env_plot = TRUE, world = TRUE, rast_return = FALSE, col_rich = NULL, ... )lets.plot.envpam( x, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, geo_plot = TRUE, env_plot = TRUE, world = TRUE, rast_return = FALSE, col_rich = NULL, ... )
x |
The output object from |
species |
A character string indicating the species name to be highlighted in both plots. |
cell_id_env |
An integer or vector of integers indicating environmental space cell(s) to be highlighted. |
cell_id_geo |
An integer or vector of integers indicating geographic cell(s) to be highlighted. |
geo_plot |
Logical. Should the geographic richness map also be plotted? Default is TRUE. |
env_plot |
Logical. Should the environmental space richness map also be plotted? Default is TRUE. |
world |
Logical. If TRUE, plots a base map using the 'wrld_simpl' object from the 'letsR' package over the geographic raster. |
rast_return |
Logical. If TRUE, returns the modified raster objects instead of plotting. |
col_rich |
A custom color ramp palette function to use for plotting richness (e.g., from |
... |
Additional arguments passed to the |
This function provides a visual summary of species richness across both geographic and environmental dimensions. Users can highlight specific species or environmental/geographical cells. When a highlight is selected, both rasters are modified to display only presences related to the selected species or cells, and all other cells are greyed out.
Bruno Vilela
lets.envpam, lets.presab, plot.PresenceAbsence
## Not run: # Load data data("Phyllomedusa") data("prec") data("temp") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Preciptation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) # Create environmental PAM res <- lets.envpam(PAM, envs) # Plot both spaces lets.plot.envpam(x = res, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, geo_plot = TRUE, world = TRUE, mar = c(4, 4, 4, 4)) # Highlight a single species lets.plot.envpam(res, species = "Phyllomedusa_atlantica") ## End(Not run)## Not run: # Load data data("Phyllomedusa") data("prec") data("temp") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Preciptation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) # Create environmental PAM res <- lets.envpam(PAM, envs) # Plot both spaces lets.plot.envpam(x = res, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, geo_plot = TRUE, world = TRUE, mar = c(4, 4, 4, 4)) # Highlight a single species lets.plot.envpam(res, species = "Phyllomedusa_atlantica") ## End(Not run)
Convert species' ranges (in shapefile format) into a presence-absence matrix based on a user-defined grid system
lets.presab( shapes, xmn = NULL, xmx = NULL, ymn = NULL, ymx = NULL, resol = NULL, remove.cells = TRUE, remove.sp = TRUE, show.matrix = FALSE, crs = "+proj=longlat +datum=WGS84", crs.grid = crs, cover = 0, presence = NULL, origin = NULL, seasonal = NULL, count = FALSE )lets.presab( shapes, xmn = NULL, xmx = NULL, ymn = NULL, ymx = NULL, resol = NULL, remove.cells = TRUE, remove.sp = TRUE, show.matrix = FALSE, crs = "+proj=longlat +datum=WGS84", crs.grid = crs, cover = 0, presence = NULL, origin = NULL, seasonal = NULL, count = FALSE )
shapes |
Object of class |
xmn |
Minimum longitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
xmx |
Maximum longitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
ymn |
Minimum latitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
ymx |
Maximum latitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
resol |
Numeric vector of length 1 or 2 to set the grid resolution. If NULL, resolution will be equivalent to 1 degree of latitude and longitude. |
remove.cells |
Logical, if |
remove.sp |
Logical, if |
show.matrix |
Logical, if |
crs |
Character representing the PROJ.4 type description of a Coordinate Reference System (map projection) of the polygons. |
crs.grid |
Character representing the PROJ.4 type description of a Coordinate Reference System (map projection) for the grid. Note that when you change this options you may probably change the extent coordinates and the resolution. |
cover |
Percentage of the cell covered by the shapefile that will be considered for presence (values between 0 and 1). |
presence |
A vector with the code numbers for the presence type to be considered in the process (for IUCN spatial data https://www.iucnredlist.org/resources/spatial-data-download, see metadata). |
origin |
A vector with the code numbers for the origin type to be considered in the process (for IUCN spatial data). |
seasonal |
A vector with the code numbers for the seasonal type to be considered in the process (for IUCN spatial data). |
count |
Logical, if |
This function creates the presence-absence matrix based on a raster
object. Depending on the cell size, extension used and number of species it
may require a lot of memory, and may take some time to process it. Thus,
during the process, if count argument is set TRUE, a counting
window will open to display the progress (i.e. the polygon/shapefile
that the function is working on). Note that the number of polygons is not the same
as the number of species (i.e. a species may have more than
one polygon/shapefiles).
The result is a list object of class PresenceAbsence
with the following objects: Presence-Absence Matrix: A matrix of
species' presence(1) and absence(0) information. The first two columns
contain the longitude (x) and latitude (y) of the cells' centroid (from the
gridded domain used); Richness Raster: A raster containing species
richness data; Species name: A character vector with species' names
contained in the matrix.
*But see the optional argument show.matrix.
Bruno Vilela & Fabricio Villalobos
## Not run: # Spatial distribution polygons of South American frogs # of genus Phyllomedusa. data(Phyllomedusa) PAM <- lets.presab(Phyllomedusa) summary(PAM) # Species richness map plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") # Map of individual species plot(PAM, name = "Phyllomedusa nordestina") ## End(Not run)## Not run: # Spatial distribution polygons of South American frogs # of genus Phyllomedusa. data(Phyllomedusa) PAM <- lets.presab(Phyllomedusa) summary(PAM) # Species richness map plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") # Map of individual species plot(PAM, name = "Phyllomedusa nordestina") ## End(Not run)
Convert species' ranges (in shapefile format and stored in particular folders) into a presence-absence matrix based on a user-defined grid. This function is specially designed to work with BirdLife Intl. shapefiles (https://www.birdlife.org). (Notice that new versions of birds spatial data are in a similar format to other groups and should be run using the lets.presab function. We will keep this function in case someone needs to use on the previous data format.)
lets.presab.birds( path, xmn = NULL, xmx = NULL, ymn = NULL, ymx = NULL, resol = NULL, remove.cells = TRUE, remove.sp = TRUE, show.matrix = FALSE, crs = "+proj=longlat +datum=WGS84", crs.grid = crs, cover = 0, presence = NULL, origin = NULL, seasonal = NULL, count = FALSE )lets.presab.birds( path, xmn = NULL, xmx = NULL, ymn = NULL, ymx = NULL, resol = NULL, remove.cells = TRUE, remove.sp = TRUE, show.matrix = FALSE, crs = "+proj=longlat +datum=WGS84", crs.grid = crs, cover = 0, presence = NULL, origin = NULL, seasonal = NULL, count = FALSE )
path |
Path location of folders with one or more species' individual
shapefiles. Shapefiles with more than one species will not work on this
function. To use multi-species shapefiles see |
xmn |
Minimum longitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
xmx |
Maximum longitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
ymn |
Minimum latitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
ymx |
Maximum latitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
resol |
Numeric vector of length 1 or 2 to set the grid resolution. If NULL, resolution will be equivalent to 1 degree of latitude and longitude. |
remove.cells |
Logical, if |
remove.sp |
Logical, if |
show.matrix |
Logical, if |
crs |
Character representing the PROJ.4 type description of a Coordinate Reference System (map projection) of the polygons. |
crs.grid |
Character representing the PROJ.4 type description of a Coordinate Reference System (map projection) for the grid. Note that when you change this options you may probably change the extent coordinates and the resolution. |
cover |
Percentage of the cell covered by the shapefile that will be considered for presence (values between 0 and 1). |
presence |
A vector with the code numbers for the presence type to be considered in the process (for IUCN spatial data https://www.iucnredlist.org/resources/spatial-data-download, see metadata). |
origin |
A vector with the code numbers for the origin type to be considered in the process (for IUCN spatial data). |
seasonal |
A vector with the code numbers for the seasonal type to be considered in the process (for IUCN spatial data). |
count |
Logical, if |
The function creates the presence-absence matrix based on a raster
file. Depending on the cell size, extension used and number of species it
may require a lot of memory, and may take some time to process it. Thus,
during the process, if count argument is set TRUE, a counting
window will open so you can see the progress (i.e. in what polygon the
function is working). Note that the number of polygons is not the same as
the number of species that you have (i.e. a species may have more than one
polygon/shapefiles).
The result is a list object of class PresenceAbsence
with the following objects: Presence-Absence Matrix: A matrix of
species' presence(1) and absence(0) information. The first two columns
contain the longitude (x) and latitude (y) of the cells' centroid (from the
gridded domain used); Richness Raster: A raster containing species
richness data; Species name: A character vector with species' names
contained in the matrix.
*But see the optional argument show.matrix.
Bruno Vilela & Fabricio Villalobos
## Not run: # Constructing a Presence/Absence matrix for birds # Attention: For your own files, omit the 'system.file' # and 'package="letsR"', these are just to get the path # to files installed with the package. path.Ramphastos <- system.file("extdata", package = "letsR") PAM <- lets.presab.birds(path.Ramphastos, xmn = -93, xmx = -29, ymn = -57, ymx = 25) # Species richness map plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Ramphastos species Richness") ## End(Not run)## Not run: # Constructing a Presence/Absence matrix for birds # Attention: For your own files, omit the 'system.file' # and 'package="letsR"', these are just to get the path # to files installed with the package. path.Ramphastos <- system.file("extdata", package = "letsR") PAM <- lets.presab.birds(path.Ramphastos, xmn = -93, xmx = -29, ymn = -57, ymx = 25) # Species richness map plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Ramphastos species Richness") ## End(Not run)
Convert species' ranges (in shapefile format) into a presence-absence matrix based on a grid in shapefile format.
lets.presab.grid( shapes, grid, sample.unit, remove.sp = TRUE, presence = NULL, origin = NULL, seasonal = NULL )lets.presab.grid( shapes, grid, sample.unit, remove.sp = TRUE, presence = NULL, origin = NULL, seasonal = NULL )
shapes |
Object of class |
grid |
Object of class SpatVector (see function
|
sample.unit |
Object of class |
remove.sp |
Logical, if |
presence |
A vector with the code numbers for the presence type to be considered in the process (for IUCN spatial data https://www.iucnredlist.org/resources/spatial-data-download, see metadata). |
origin |
A vector with the code numbers for the origin type to be considered in the process (for IUCN spatial data). |
seasonal |
A vector with the code numbers for the seasonal type to be considered in the process (for IUCN spatial data). |
This function is an alternative way to create a presence absence matrix when users already have their own grid.
The result is a list containing two objects:
(I) A matrix the species presence (1) and absence (0) values per sample unity.
(II) The original grid.
Bruno Vilela & Fabricio Villalobos
## Not run: # Species polygons data("Phyllomedusa") data("wrld_simpl") # Grid sp.r <- terra::as.polygons(terra::rast(resol = 5, crs = terra::crs(Phyllomedusa), xmin = -93, xmax = -29, ymin = -57, ymax = 15)) sp.r$ID <- 1:length(sp.r) # PAM resu <- lets.presab.grid(Phyllomedusa, sp.r, "ID") # Plot rich_plus1 <- rowSums(resu$PAM[, -1]) + 1 colfunc <- colorRampPalette(c("#fff5f0", "#fb6a4a", "#67000d")) colors <- c("white", colfunc(max(rich_plus1))) plot(resu$grid, border = "gray40", col = colors[rich_plus1]) plot(sf::st_geometry(wrld_simpl), add = TRUE) ## End(Not run)## Not run: # Species polygons data("Phyllomedusa") data("wrld_simpl") # Grid sp.r <- terra::as.polygons(terra::rast(resol = 5, crs = terra::crs(Phyllomedusa), xmin = -93, xmax = -29, ymin = -57, ymax = 15)) sp.r$ID <- 1:length(sp.r) # PAM resu <- lets.presab.grid(Phyllomedusa, sp.r, "ID") # Plot rich_plus1 <- rowSums(resu$PAM[, -1]) + 1 colfunc <- colorRampPalette(c("#fff5f0", "#fb6a4a", "#67000d")) colors <- c("white", colfunc(max(rich_plus1))) plot(resu$grid, border = "gray40", col = colors[rich_plus1]) plot(sf::st_geometry(wrld_simpl), add = TRUE) ## End(Not run)
Convert species' occurrences points into a presence-absence matrix based on a grid in shapefile format.
lets.presab.grid.points( xy, species, grid, sample.unit, remove.sp = TRUE, abundance = TRUE )lets.presab.grid.points( xy, species, grid, sample.unit, remove.sp = TRUE, abundance = TRUE )
xy |
A matrix with geographic coordinates of species occurrences, first column is the longitude (or x), and the second latitude (or y). |
species |
Character vector with species names, in the same order as the coordinates. |
grid |
Object of class SpatVector (see function
|
sample.unit |
Object of class |
remove.sp |
Logical, if |
abundance |
Logical. If TRUE, the resulting matrix will display number of occurrences per species in each cell. If FALSE, the resulting matrix will show presence-absence values. |
This function is an alternative way to create a presence absence matrix when users already have their own grid.
The result is a list containing two objects:
(I) A matrix the species presence (1) and absence (0) values per sample unity.
(II) The original grid.
Bruno Vilela & Fabricio Villalobos
## Not run: # Species polygons data("wrld_simpl") # Grid crs = "+proj=longlat +datum=WGS84 +no_defs" sp.r <- terra::as.polygons(terra::rast( resol = 5, crs = crs, xmin = -93, xmax = -29, ymin = -57, ymax = 15 )) sp.r$ID <- 1:length(sp.r) # Occurrence Points N = 20 species <- c(rep("sp1", N), rep("sp2", N), rep("sp3", N), rep("sp4", N)) x <- runif(N * 4, min = -69, max = -51) y <- runif(N * 4, min = -23, max = -4) xy <- cbind(x, y) # PAM resu <- lets.presab.grid.points(xy, species, sp.r, "ID", abundance = FALSE) # Plot rich_plus1 <- rowSums(resu$PAM[, -1, drop = FALSE]) + 1 colfunc <- colorRampPalette(c("#fff5f0", "#fb6a4a", "#67000d")) colors <- c("white", colfunc(max(rich_plus1))) occs <- terra::vect(xy, crs = crs) plot(resu$grid, border = "gray40", col = colors[rich_plus1]) plot(sf::st_geometry(wrld_simpl), add = TRUE) plot(occs, cex = 0.5, col = rep(1:4, each = N), add = T) ## End(Not run)## Not run: # Species polygons data("wrld_simpl") # Grid crs = "+proj=longlat +datum=WGS84 +no_defs" sp.r <- terra::as.polygons(terra::rast( resol = 5, crs = crs, xmin = -93, xmax = -29, ymin = -57, ymax = 15 )) sp.r$ID <- 1:length(sp.r) # Occurrence Points N = 20 species <- c(rep("sp1", N), rep("sp2", N), rep("sp3", N), rep("sp4", N)) x <- runif(N * 4, min = -69, max = -51) y <- runif(N * 4, min = -23, max = -4) xy <- cbind(x, y) # PAM resu <- lets.presab.grid.points(xy, species, sp.r, "ID", abundance = FALSE) # Plot rich_plus1 <- rowSums(resu$PAM[, -1, drop = FALSE]) + 1 colfunc <- colorRampPalette(c("#fff5f0", "#fb6a4a", "#67000d")) colors <- c("white", colfunc(max(rich_plus1))) occs <- terra::vect(xy, crs = crs) plot(resu$grid, border = "gray40", col = colors[rich_plus1]) plot(sf::st_geometry(wrld_simpl), add = TRUE) plot(occs, cex = 0.5, col = rep(1:4, each = N), add = T) ## End(Not run)
Convert species' occurrences points into a presence-absence matrix based on a user-defined grid.
lets.presab.points( xy, species, xmn = NULL, xmx = NULL, ymn = NULL, ymx = NULL, resol = NULL, remove.cells = TRUE, remove.sp = TRUE, show.matrix = FALSE, crs = "+proj=longlat +datum=WGS84", count = FALSE )lets.presab.points( xy, species, xmn = NULL, xmx = NULL, ymn = NULL, ymx = NULL, resol = NULL, remove.cells = TRUE, remove.sp = TRUE, show.matrix = FALSE, crs = "+proj=longlat +datum=WGS84", count = FALSE )
xy |
A matrix with geographic coordinates of species occurrences, first column is the longitude (or x), and the second latitude (or y). |
species |
Character vector with species names, in the same order as the coordinates. |
xmn |
Minimum longitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
xmx |
Maximum longitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
ymn |
Minimum latitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
ymx |
Maximum latitude used to construct the grid in which the matrix will be based (i.e. the [gridded] geographic domain of interest). If NULL, limits will be calculated based on the limits of the shapes object. |
resol |
Numeric vector of length 1 or 2 to set the grid resolution. If NULL, resolution will be equivalent to 1 degree of latitude and longitude. |
remove.cells |
Logical, if |
remove.sp |
Logical, if |
show.matrix |
Logical, if |
crs |
Character representing the PROJ.4 type description of a Coordinate Reference System (map projection) of the polygons. |
count |
Logical, if |
The function creates the presence-absence matrix based on a raster
file. Depending on the cell size, extension used and number of species it
may require a lot of memory, and may take some time to process it. Thus,
during the process, if count argument is set TRUE, a counting
window will open so you can see the progress (i.e. in what polygon the
function is working). Note that the number of polygons is not the same as
the number of species that you have (i.e. a species may have more than one
polygon/shapefiles).
The result is a list object of class PresenceAbsence
with the following objects: Presence-Absence Matrix: A matrix of
species' presence(1) and absence(0) information. The first two columns
contain the longitude (x) and latitude (y) of the cells' centroid (from the
gridded domain used); Richness Raster: A raster containing species
richness data; Species name: A character vector with species' names
contained in the matrix.
*But see the optional argument show.matrix.
Bruno Vilela & Fabricio Villalobos
## Not run: species <- c(rep("sp1", 100), rep("sp2", 100), rep("sp3", 100), rep("sp4", 100)) x <- runif(400, min = -69, max = -51) y <- runif(400, min = -23, max = -4) xy <- cbind(x, y) PAM <- lets.presab.points(xy, species, xmn = -93, xmx = -29, ymn = -57, ymx = 15) summary(PAM) # Species richness map plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Species richness map (simulated)") # Map of the specific species plot(PAM, name = "sp1") ## End(Not run)## Not run: species <- c(rep("sp1", 100), rep("sp2", 100), rep("sp3", 100), rep("sp4", 100)) x <- runif(400, min = -69, max = -51) y <- runif(400, min = -23, max = -4) xy <- cbind(x, y) PAM <- lets.presab.points(xy, species, xmn = -93, xmx = -29, ymn = -57, ymx = 15) summary(PAM) # Species richness map plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Species richness map (simulated)") # Map of the specific species plot(PAM, name = "sp1") ## End(Not run)
This function calculates species' range sizes from a PresenceAbsence object or directly from the species' shapefiles.
lets.rangesize( x, species_name = NULL, coordinates = "geographic", units = "cell" )lets.rangesize( x, species_name = NULL, coordinates = "geographic", units = "cell" )
x |
A |
species_name |
Species names in the same order as in the
|
coordinates |
"geographical" or "planar". Indicate whether the shapefile
has geographical or planar coordinates(only needed if x is a
|
units |
"cell" or "squaremeter". Indicate if the size units wanted are
in number of cells occupied or in square meters(only needed if x is a
|
The result is a matrix with the range size of each species. If the range size accounts for the earth curvature (Yes or No) or its size unit may differ for each argument combination:
1) SpatVector & geographical = Square meters. Yes.
2) SpatVector & planar = Square meters. No.
3) PresenceAbsence & cell = number of cells. No.
4) PresenceAbsence & squaremeter = Square meters. Yes.
Bruno Vilela
## Not run: # SpatialPolygonsDataFrame & geographical data(Phyllomedusa) rangesize <- lets.rangesize(x = Phyllomedusa, coordinates = "geographic") # SpatialPolygonsDataFrame & planar rangesize2 <- lets.rangesize(x = Phyllomedusa, coordinates = "planar") # PresenceAbsence & cell data(PAM) rangesize3 <- lets.rangesize(x = PAM, units = "cell") # PresenceAbsence & squaremeter rangesize4 <- lets.rangesize(x = PAM, units = "squaremeter") ## End(Not run)## Not run: # SpatialPolygonsDataFrame & geographical data(Phyllomedusa) rangesize <- lets.rangesize(x = Phyllomedusa, coordinates = "geographic") # SpatialPolygonsDataFrame & planar rangesize2 <- lets.rangesize(x = Phyllomedusa, coordinates = "planar") # PresenceAbsence & cell data(PAM) rangesize3 <- lets.rangesize(x = PAM, units = "cell") # PresenceAbsence & squaremeter rangesize4 <- lets.rangesize(x = PAM, units = "squaremeter") ## End(Not run)
Save an external representation of a PresenceAbsence object to
the specified file. The object can be read back from the file at a later
date by using the function lets.load.
lets.save(pam, ...)lets.save(pam, ...)
pam |
A PresenceAbsence object. |
... |
other arguments passed to the function |
Bruno Vilela
## Not run: data(PAM) lets.save(PAM, file = "PAM.RData") PAM <- lets.load(file = "PAM.RData") ## End(Not run)## Not run: data(PAM) lets.save(PAM, file = "PAM.RData") PAM <- lets.load(file = "PAM.RData") ## End(Not run)
Filter species shapefiles by origin, presence, and seasonal type (following IUCN types: https://www.iucnredlist.org/resources/spatial-data-download, see metadata).
lets.shFilter(shapes, presence = NULL, origin = NULL, seasonal = NULL)lets.shFilter(shapes, presence = NULL, origin = NULL, seasonal = NULL)
shapes |
Object of class |
presence |
A vector with the code numbers for the presence type to be considered in the process (for IUCN spatial data https://www.iucnredlist.org/resources/spatial-data-download, see metadata). |
origin |
A vector with the code numbers for the origin type to be considered in the process (for IUCN spatial data). |
seasonal |
A vector with the code numbers for the seasonal type to be considered in the process (for IUCN spatial data). |
Presence codes: (1) Extant, (2) Probably Extant, (3) Possibly Extant, (4) Possibly Extinct, (5) Extinct (post 1500) & (6) Presence Uncertain.
Origin codes: (1) Native, (2) Reintroduced, (3) Introduced, (4) Vagrant & (5) Origin Uncertain.
Seasonal codes: (1) Resident, (2) Breeding Season, (3) Non-breeding Season, (4) Passage & (5) Seasonal Occurrence Uncertain.
More info in the shapefiles' metadata.
The result is the shapefile(s) filtered according to the selected types. If the filters remove all polygons, the result will be NULL.
Bruno Vilela
## Not run: data(Phyllomedusa) filtered_shape <- lets.shFilter( shape = Phyllomedusa, presence = 1, origin = 1, seasonal = 1) if (!is.null(filtered_shape)) { plot(filtered_shape, col = "lightgreen", border = "darkgreen") } ## End(Not run)## Not run: data(Phyllomedusa) filtered_shape <- lets.shFilter( shape = Phyllomedusa, presence = 1, origin = 1, seasonal = 1) if (!is.null(filtered_shape)) { plot(filtered_shape, col = "lightgreen", border = "darkgreen") } ## End(Not run)
Subset a PresenceAbsence object based on species character vector provided by the user.
lets.subsetPAM(x, species, remove.cells = TRUE)lets.subsetPAM(x, species, remove.cells = TRUE)
x |
A |
species |
Character vector with species names to subset the |
remove.cells |
Logical, if |
The result is an object of class PresenceAbsence subseted.
Bruno Vilela
## Not run: data(PAM) # PAM before subset plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") # Subset PAM to the first 20 species PAMsub <- lets.subsetPAM(PAM, PAM[[3]][1:20]) plot(PAMsub, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") ## End(Not run)## Not run: data(PAM) # PAM before subset plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") # Subset PAM to the first 20 species PAMsub <- lets.subsetPAM(PAM, PAM[[3]][1:20]) plot(PAMsub, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") ## End(Not run)
Subsets an attribute-based presence-absence matrix (PAM) generated by
lets.attrpam by retaining only a selected set of species.
Species not included in names are removed from the PAM, while the
first three columns of the PAM table are always preserved because they store
attribute-space cell metadata. After subsetting, species richness is
recalculated for each attribute-space cell and written back to the associated
raster object.
lets.subsetPAMatt(x, species, remove.cells = TRUE)lets.subsetPAMatt(x, species, remove.cells = TRUE)
x |
A PAM in attribute space produced by
|
species |
A character vector with species names to retain in the PAM. |
remove.cells |
Logical. If |
Optionally, attribute-space cells with zero richness after subsetting can be removed from the tabular component of the PAM.
The function assumes that the first three columns of x[[1]] contain
non-species information and therefore always preserves them during
subsetting. Richness is recalculated as the row sum across all retained
species columns.
If none of the supplied species names match the species present in the PAM, the function stops with an error.
A list with the same structure as the input object:
x[[1]]: the subsetted attribute PAM table.
x[[2]]: the attribute-space raster with richness values updated
according to the retained species.
lets.attrpam, lets.plot.attrpam
## Not run: n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) x <- data.frame(Species, trait_a, trait_b) pam_att <- lets.attrpam(x, n_bins = 30) names <- sample(Species, 200) pam_sub <- lets.subsetPAMatt(pam_att, names) lets.plot.attrpam(pam_sub) ## End(Not run)## Not run: n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) x <- data.frame(Species, trait_a, trait_b) pam_att <- lets.attrpam(x, n_bins = 30) names <- sample(Species, 200) pam_sub <- lets.subsetPAMatt(pam_att, names) lets.plot.attrpam(pam_sub) ## End(Not run)
Subsets an environmental-space presence-absence matrix (PAM) generated by
lets.envpam by retaining only a selected set of species.
Species not included in species are removed from both tabular
components of the object, and species richness is recalculated and written
back to the corresponding raster layers.
lets.subsetPAMenv(x, species, remove.cells = TRUE)lets.subsetPAMenv(x, species, remove.cells = TRUE)
x |
An environmental PAM produced by |
species |
A character vector with species names to retain in the PAM. |
remove.cells |
Logical. If |
Optionally, cells with zero richness after subsetting can be removed from the tabular components.
If none of the supplied species names match the species present in the PAM, the function stops with an error before modifying the object.
A list with the same structure as the input object:
x[[1]]: the subsetted env PAM table.
x[[2]]: the subsetted geo PAM table.
x[[3]]: the raster associated with env PAM, updated with
recalculated richness values.
x[[4]]: the raster associated with geo PAM, updated with
recalculated richness values.
lets.envpam, lets.plot.envpam,
lets.presab, lets.addvar
## Not run: data("Phyllomedusa") data("prec") data("temp") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) res <- lets.envpam(PAM, envs) lets.plot.envpam( x = res, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, plot.grid = TRUE, world = TRUE, mar = c(4, 4, 4, 4) ) sub <- sample(PAM$Species_name, 10) pam_sub <- lets.subsetPAMenv(res, sub) lets.plot.envpam(pam_sub) ## End(Not run)## Not run: data("Phyllomedusa") data("prec") data("temp") prec <- unwrap(prec) temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, vect(wrld_simpl)) res <- lets.envpam(PAM, envs) lets.plot.envpam( x = res, species = NULL, cell_id_env = NULL, cell_id_geo = NULL, plot.grid = TRUE, world = TRUE, mar = c(4, 4, 4, 4) ) sub <- sample(PAM$Species_name, 10) pam_sub <- lets.subsetPAMenv(res, sub) lets.plot.envpam(pam_sub) ## End(Not run)
Based on a Presence-Absence matrix with added variables
(see lets.addvar), this function summarizes the values of
such variable(s) per species (across the species' occupied cells. i.e.
within their ranges).
lets.summarizer(x, pos, xy = TRUE, fun = mean, ...)lets.summarizer(x, pos, xy = TRUE, fun = mean, ...)
x |
Presence-absence matrix with variables added. |
pos |
Column position of the variables of interest. |
xy |
Logical, if |
fun |
Function to be used to summarize the variable per species.
Default is |
... |
Other parameters passed to the function defined in |
Bruno Vilela & Fabricio Villalobos
Villalobos, F. and Arita, H.T. 2010. The diversity field of New World leaf-nosed bats (Phyllostomidae). Global Ecology and Biogeography. 19, 200-211.
## Not run: data(PAM) data(temp) temp <- terra::unwrap(temp) pamvar <- lets.addvar(PAM, temp) resu <- lets.summarizer(x = pamvar, pos = ncol(pamvar), xy = TRUE) ## End(Not run)## Not run: data(PAM) data(temp) temp <- terra::unwrap(temp) pamvar <- lets.addvar(PAM, temp) resu <- lets.summarizer(x = pamvar, pos = ncol(pamvar), xy = TRUE) ## End(Not run)
Given a presence–absence matrix in either attribute space (from
lets.attrpam) or environmental space (from
lets.envpam) and a table of per-cell descriptors
(from lets.attrcells or lets.envcells),
this function aggregates each descriptor across the set of cells
occupied by each species, using a user-supplied summary function
(e.g., mean, median, sum).
lets.summaryze.cells(x, y, func = mean)lets.summaryze.cells(x, y, func = mean)
x |
A list returned by |
y |
A |
func |
A summary function to aggregate a descriptor across the cells
occupied by a species (default |
Summarize per-cell descriptors to species-level values
Internally, for each species column in x[[1]] (starting at column 4),
the function builds a logical mask of occupied cells (> 0). It then subsets
the descriptor table y to those rows and applies func column-wise
to y[occupied, -1] (dropping the ID column). Missing values are removed
with stats::na.omit prior to aggregation.
A data.frame with one row per species and one column per descriptor,
containing the aggregated (e.g., mean) value of each descriptor across all
cells where that species is present. The first column, Species, holds
the species names copied from colnames(x[[1]])[4:ncol(x[[1]])].
lets.attrpam, lets.envpam,
lets.attrcells, lets.envcells
## Not run: ## -------------------------- ## ATTRIBUTE SPACE WORKFLOW ## -------------------------- set.seed(1) n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) df <- data.frame(Species, trait_a, trait_b) # Build AttrPAM and compute per-cell descriptors x_attr <- lets.attrpam(df, n_bins = 30) y_attr <- lets.attrcells(x_attr) # Summarize descriptors per species (e.g., mean across occupied cells) head(lets.summaryze.cells(x_attr, y_attr, func = mean)) ## ------------------------------ ## ENVIRONMENTAL SPACE WORKFLOW ## ------------------------------ data("Phyllomedusa"); data("prec"); data("temp") prec <- unwrap(prec); temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, terra::vect(wrld_simpl)) res_env <- lets.envpam(PAM, envs, n_bins = 30) y_env <- lets.envcells(res_env, perc = 0.2) # Summarize environmental-space descriptors per species head(lets.summaryze.cells(res_env, y_env, func = mean)) ## End(Not run)## Not run: ## -------------------------- ## ATTRIBUTE SPACE WORKFLOW ## -------------------------- set.seed(1) n <- 2000 Species <- paste0("sp", 1:n) trait_a <- rnorm(n) trait_b <- trait_a * 0.2 + rnorm(n) df <- data.frame(Species, trait_a, trait_b) # Build AttrPAM and compute per-cell descriptors x_attr <- lets.attrpam(df, n_bins = 30) y_attr <- lets.attrcells(x_attr) # Summarize descriptors per species (e.g., mean across occupied cells) head(lets.summaryze.cells(x_attr, y_attr, func = mean)) ## ------------------------------ ## ENVIRONMENTAL SPACE WORKFLOW ## ------------------------------ data("Phyllomedusa"); data("prec"); data("temp") prec <- unwrap(prec); temp <- unwrap(temp) PAM <- lets.presab(Phyllomedusa, remove.cells = FALSE) envs <- lets.addvar(PAM, c(temp, prec), onlyvar = TRUE) colnames(envs) <- c("Temperature", "Precipitation") wrld_simpl <- get(utils::data("wrld_simpl", package = "letsR")) PAM <- lets.pamcrop(PAM, terra::vect(wrld_simpl)) res_env <- lets.envpam(PAM, envs, n_bins = 30) y_env <- lets.envcells(res_env, perc = 0.2) # Summarize environmental-space descriptors per species head(lets.summaryze.cells(res_env, y_env, func = mean)) ## End(Not run)
Transform each element of a vector.
lets.transf(x, y, z, NUMERIC = TRUE)lets.transf(x, y, z, NUMERIC = TRUE)
x |
A vector to be transformed. |
y |
levels to be transformed. |
z |
The value to be atributed to each level (same order as y). |
NUMERIC |
logical, if |
Return a vector with changed values.
Bruno Vilela
## Not run: status <- sample(c("EN","VU", "NT", "CR", "DD", "LC"), 30, replace=TRUE) TE <- "Threatened" NT <- "Non-Threatened" new <- c(TE, TE, NT, TE, "Data Deficient", NT) old <- c("EN","VU", "NT", "CR", "DD", "LC") statustrans <- lets.transf(status, old, new, NUMERIC=FALSE) ## End(Not run)## Not run: status <- sample(c("EN","VU", "NT", "CR", "DD", "LC"), 30, replace=TRUE) TE <- "Threatened" NT <- "Non-Threatened" new <- c(TE, TE, NT, TE, "Data Deficient", NT) old <- c("EN","VU", "NT", "CR", "DD", "LC") statustrans <- lets.transf(status, old, new, NUMERIC=FALSE) ## End(Not run)
PresenceAbsence object obtained using the function lets.presab
for the Geographic distribution of the South American frog genus Phyllomedusa.
PAMPAM
A PresenceAbsence object
Generated from IUCN Spatial Data - https://www.iucnredlist.org/. 2014.
Geographic distribution of the South American frog genus Phyllomedusa.
PhyllomedusaPhyllomedusa
A simple feature collection for 32 species with 46 features and 4 fields.
Scientific name
IUCN Red List distributional code
IUCN Red List distributional code
IUCN Red List distributional code
See the IUCN Red List Attribute Information for Species Ranges.
IUCN - https://www.iucnredlist.org/. 2014.
Plots species richness map from an object of class PresenceAbsence or a particular species' map.
## S3 method for class 'PresenceAbsence' plot(x, name = NULL, world = TRUE, col_rich = NULL, col_name = "red", ...)## S3 method for class 'PresenceAbsence' plot(x, name = NULL, world = TRUE, col_rich = NULL, col_name = "red", ...)
x |
An object of class |
name |
A character specifying a species to be ploted instead of the complete species richness map. |
world |
If |
col_rich |
Color function (e.g. |
col_name |
The color to use when ploting single species. |
... |
Other parameters pass to the plot function. |
Bruno Vilela
## Not run: data(PAM) plot(PAM) plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") plot(PAM, name = "Phyllomedusa atelopoides") plot(PAM, name = "Phyllomedusa azurea") ## End(Not run)## Not run: data(PAM) plot(PAM) plot(PAM, xlab = "Longitude", ylab = "Latitude", main = "Phyllomedusa species richness") plot(PAM, name = "Phyllomedusa atelopoides") plot(PAM, name = "Phyllomedusa azurea") ## End(Not run)
Annual Precipitation in mm for the world in 10 arc min of resolution.
precprec
A PackedStatRaster object.
Data was modified from WorldClim (https://worldclim.org/, downloaded 10/2024).
Hijmans, R.J., S.E. Cameron, J.L. Parra, P.G. Jones and A. Jarvis, 2005. Very high resolution interpolated climate surfaces for global land areas. International Journal of Climatology 25: 1965-1978.
The PresenceAbsence is a new S3 object class created and
used inside the letsR package. This object class is used to
store information on species distribution within a geographic domain in the
form of a presence-absence matrix. In addition, the PresenceAbsence
object also contains other essential information (e.g. user-defined grid
cell system, including resolution, projection, datum, and extent) necessary
for other analysis performed with the package's functions.
Creating a PresenceAbsence object
A
PresenceAbsence object can be generated using the following
functions:
- lets.presab
- lets.presab.birds
- lets.presab.points
The PresenceAbsence information
The result is a list
object of class PresenceAbsence that includes the following
objects:
- Presence_and_Absence_Matrix: A matrix of species' presence(1) and absence(0)
information. The first two columns contain the longitude (x) and latitude (y)
of the cells' centroid (from the gridded domain used);
- Richness_Raster: A raster containing species richness information across
the geographic domain, which can be used to map the observed geographic
gradient in species richness;
- Species_name: A character vector with species' names contained in
the matrix.
Each of the objects can be obtained usign the standard
subsetting operators that are commonly applied to a list object (i.e.
'[[' and '$').
letsR functions applied to a PresenceAbsence object
The following
functions from the letsR package can be directly applied to a
PresenceAbsence:
- lets.addpoly
- lets.addvar
- lets.distmat
- lets.field
- lets.gridirizer
- lets.maplizer
- lets.midpoint
- lets.overlap
- lets.pamcrop
- lets.rangesize
Generic functions applied to a PresenceAbsence object
The
following generic functions can be directly applied to the
PresenceAbsence object.
- print (print.PresenceAbsence)
- summary (summary.PresenceAbsence)
- plot (plot.PresenceAbsence)
Print for objects of class PresenceAbsence.
## S3 method for class 'PresenceAbsence' print(x, ...)## S3 method for class 'PresenceAbsence' print(x, ...)
x |
an object of class |
... |
Other print parameters. |
Bruno Vilela
Print summary for objects of class PresenceAbsence.
## S3 method for class 'PresenceAbsence' print.summary(x, ...)## S3 method for class 'PresenceAbsence' print.summary(x, ...)
x |
an object of class |
... |
Other print parameters. |
Bruno Vilela
Summary for objects of class PresenceAbsence.
## S3 method for class 'PresenceAbsence' summary(object, ...)## S3 method for class 'PresenceAbsence' summary(object, ...)
object |
an object of class |
... |
additional arguments affecting the summary produced. |
Bruno Vilela
Mean temperature raster in degrees Celsius (multiplied by 100) for the world in 10 arc min of resolution.
temptemp
A PackedStatRaster object.
Data was modified from WorldClim (https://worldclim.org/, downloaded 05/2014).
Hijmans, R.J., S.E. Cameron, J.L. Parra, P.G. Jones and A. Jarvis, 2005. Very high resolution interpolated climate surfaces for global land areas. International Journal of Climatology 25: 1965-1978.
World map in sf format. Obtained from maptools and converted to sf.
wrld_simplwrld_simpl
A simple feature collection with 246 features and 11 fields.
Now available from https://github.com/nasa/World-Wind-Java/tree/master/WorldWind/testData/shapefiles.