### msr example: setup and Moran's I test Source: https://github.com/adeverse/adespatial/blob/master/man/msr.Rd Loads spdep, creates a random matrix and spatial weights, then computes Moran's I statistic for the first column. ```r library(spdep) x1 <- matrix(rnorm(81*5), nrow = 81) lw1 <- nb2listw(cell2nb(9, 9)) moran.mc(x1[,1], lw1, 2)$statistic ``` -------------------------------- ### View the adespatial tutorial vignette Source: https://github.com/adeverse/adespatial/blob/master/README.md Opens the package vignette after installation to provide an overview of the package's functions. ```r vignette("tutorial", package = "adespatial") ``` -------------------------------- ### Install development version from GitHub with remotes Source: https://github.com/adeverse/adespatial/blob/master/README.md Requires the remotes package and a working development environment (Rtools on Windows, Xcode on Mac, or a compiler and development libraries on Linux). ```r remotes::install_github("adeverse/adespatial") ``` -------------------------------- ### Example: geoXY with gpsObject1 data Source: https://github.com/adeverse/adespatial/blob/master/man/geoXY.Rd Example usage loading a GPS object and computing coordinates in kilometers, then plotting them with equal aspect ratio. ```r load(system.file("extdata/gpsObject1.rda", package = "adespatial")) xy <- geoXY(gpsObject1$latitude, gpsObject1$longitude, unit = 1000) plot(xy[,1], xy[,2], asp = 1) ``` -------------------------------- ### Example: Create grid and generate response variable Y Source: https://github.com/adeverse/adespatial/blob/master/man/listw.select.Rd Example from the listw.select help page. Creates a 15x15 grid, generates a response variable Y structured at broad scale by a linear combination of the first three MEM variables with added normal noise. Requires the spdep package. ```R if(require(spdep)) { ### Create a grid of 15 x 15: grid <- expand.grid(x = seq(1, 15, 1), y = seq(1, 15, 1)) ### Generate a response variable Y structured at broad scale by linear combination of ### the first three MEM variables to which a normal noise is added: nb <- cell2nb(nrow = 15, ncol = 15, "queen") lw <- nb2listw(nb, style = "B") MEM <- scores.listw(lw, MEM.autocor = "positive") ``` -------------------------------- ### Install stable version from CRAN Source: https://github.com/adeverse/adespatial/blob/master/README.md Installs the stable release of adespatial from CRAN. ```r install.packages("adespatial") ``` -------------------------------- ### Example: chooseCN with mafragh data Source: https://github.com/adeverse/adespatial/blob/master/man/chooseCN.Rd Example usage of chooseCN with the mafragh dataset from ade4. Requires ade4 package. Creates four connection networks (types 1-4) and plots them in a 2x2 layout. Duplicated locations are not accepted for types 1-4 and will cause an error. ```R if(require("ade4", quietly = TRUE)){ data(mafragh) oldpar <- par(mfrow=c(2,2)) cn1 <- chooseCN(mafragh$xy,ask=FALSE,type=1) cn2 <- chooseCN(mafragh$xy,ask=FALSE,type=2) cn3 <- chooseCN(mafragh$xy,ask=FALSE,type=3) cn4 <- chooseCN(mafragh$xy,ask=FALSE,type=4) par(oldpar) } ``` -------------------------------- ### test.W usage and examples Source: https://github.com/adeverse/adespatial/blob/master/man/test.W.Rd The test.W function is deprecated; use listw.candidates and listw.select instead. The examples show how to test a binary spatial weighting matrix, a simple distance-based weighting function, and a weighting function with varying parameters. ```R test.W( Y, nb, xy, MEM.autocor = c("all", "positive", "negative"), f = NULL, ... ) ``` ```R if(require(ade4) & require(spdep)){ data(oribatid) # Hellinger transformation fau <- sqrt(oribatid$fau / outer(apply(oribatid$fau, 1, sum), rep(1, ncol(oribatid$fau)), "*")) # remove gradient effect faudt <- resid(lm(as.matrix(fau) ~ as.matrix(oribatid$xy))) # test a binary spatial weighting matrix nbtri <- tri2nb(as.matrix(oribatid$xy)) tri.res <- test.W(faudt, nbtri) maxi <- max(unlist(nbdists(nbtri, as.matrix(oribatid$xy)))) # test a simple spatial weighting function of the distance f1 <- function(x) {1-(x)/(maxi)} tri.f1 <- test.W(faudt, nbtri, f = f1, xy = as.matrix(oribatid$xy)) # test a spatial weighting function with various values of parameters f2 <- function(x,dmax,y) {1-(x^y)/(dmax)^y} tri.f2 <- test.W(faudt,nbtri, f = f2, y = 2:10, dmax = maxi, xy = as.matrix(oribatid$xy)) } ``` -------------------------------- ### msr example: singleton method Source: https://github.com/adeverse/adespatial/blob/master/man/msr.Rd Generates 9 replicates using the 'singleton' method and checks their Moran's I statistics. ```r ## singleton x1.1 <- msr(x1[,1], lw1, nrepet = 9, method = "singleton") apply(x1.1, 2, function(x) moran.mc(x, listw = lw1, nsim = 2)$statistic) ``` -------------------------------- ### Load adespatial library Source: https://github.com/adeverse/adespatial/blob/master/README.md Loads the adespatial package into the R session. ```r library("adespatial") ``` -------------------------------- ### forward.sel function usage and example Source: https://github.com/adeverse/adespatial/blob/master/man/forward.sel.Rd Usage of the forward.sel function with its parameters. The example creates random matrices x and y and calls forward.sel with nperm=99 and alpha=0.5. ```R forward.sel( Y, X, K = nrow(X) - 1, R2thresh = 0.99, adjR2thresh = 0.99, nperm = 999, R2more = 0.001, alpha = 0.05, Xscale = TRUE, Ycenter = TRUE, Yscale = FALSE, verbose = TRUE ) ``` ```R x <- matrix(rnorm(30),10,3) y <- matrix(rnorm(50),10,5) forward.sel(y,x,nperm=99, alpha = 0.5) ``` -------------------------------- ### Example of using MEM.T and checking output size Source: https://github.com/adeverse/adespatial/blob/master/man/stimodels.Rd Creates a dbMEM.T matrix for 6 sites and 5 time points, then verifies the dimensions of the resulting matrix. ```R dbMEM.T <- MEM.T(s=6, tt=5) # Check the size of the dbMEM.T output matrix dim(dbMEM.T) ``` -------------------------------- ### msr example: pair method Source: https://github.com/adeverse/adespatial/blob/master/man/msr.Rd Generates 9 replicates using the 'pair' method and checks their Moran's I statistics. ```r ## pair x1.3 <- msr(x1[,1], lw1, nrepet = 9, method = "pair") apply(x1.3, 2, function(x) moran.mc(x, listw = lw1, nsim = 2)$statistic) ``` -------------------------------- ### Example 4.1: Compute dbMEMs and pass to stimodels as COD.S Source: https://github.com/adeverse/adespatial/blob/master/man/stimodels.Rd Explicitly compute dbMEMs for a regular transect of 22 sites using adespatial's dbmem, repeat them Ti-1 times to match Ti=10 repeats, then pass the matrix to stimodels via COD.S. Results should match Example 1's output except P-values may vary slightly. ```R dbMEM.S1 <- as.matrix(dbmem(1:22)) dbMEM.S10 <- dbMEM.S1 for(j in 2:10) dbMEM.S10 <- rbind(dbMEM.S10, dbMEM.S1) out.5 <- stimodels(trich.log, S=22, Ti=10, model="5", COD.S=dbMEM.S10, nperm=999) ``` -------------------------------- ### Build binary matrix using link argument Source: https://github.com/adeverse/adespatial/blob/master/man/aem.build.binary.Rd Builds a site-by-edge binary matrix by providing an edge list via the link argument. The example uses edges from site 1 to all other sites. The default rm.same.y=TRUE applies. ```R edges<-expand.grid(1,2:25) bin.mat <- aem.build.binary(coords=xy,link=edges) str(bin.mat) ``` -------------------------------- ### Modified example with disjoint clusters Source: https://github.com/adeverse/adespatial/blob/master/man/constr.hclust.Rd Reuses the same response variable and coordinates as the previous example but with a different edge matrix to produce disjoint clusters. The code defines the data and coordinates again. ```R var = c(1.5, 0.2, 5.1, 3.0, 2.1, 1.4) ex.Y = data.frame(var) ``` ```R x.coo = c(-1, -2, -0.5, 0.5, 2, 1) y.coo = c(-2, -1, 0, 0, 1, 2) ex.xy = data.frame(x.coo, y.coo) ``` -------------------------------- ### Example: msr on fourthcorner with spatial and phylogenetic constraints Source: https://github.com/adeverse/adespatial/blob/master/man/msr.4thcorner.Rd Demonstrates running msr on a fourthcorner object with spatial weights and phylogenetic tree. Requires ade4, adephylo, spdep, and ape packages. The example uses the mafragh dataset, creates a fourthcorner object with 49 permutations, reads a phylogenetic tree, converts neighborhood to listw, and applies msr. ```r if(require("ade4", quietly = TRUE) & require("adephylo", quietly = TRUE) & require("spdep", quietly = TRUE) & require("ape", quietly = TRUE)){ data(mafragh, package = "ade4") fr1 <- fourthcorner(mafragh$env, mafragh$flo, mafragh$traits$tabQuantitative, nrepet = 49) phy <- read.tree(text = mafragh$tre) lw <- nb2listw(mafragh$nb) fr1.msr <- msr(fr1, listwORorthobasis = lw, phyloORorthobasis = phy) fr1 fr1.msr } ``` -------------------------------- ### Temporal example: aem.weight.edges() with default rotation Source: https://github.com/adeverse/adespatial/blob/master/man/aem.weight.edges.Rd Computes edge weights for a temporal AEM construction using a linear sequence of dates. Requires 'dates' and 'autocor.limit' objects from a prior example. The result is assigned to 'wtime' and printed. ```R n <- length(dates) nb <- cell2nb(1, n) xy.dates <- cbind(1:n, rep(1, n), dates) (wtime <- aem.weight.edges(nb, xy.dates, alpha=2, max.d=autocor.limit)) ``` -------------------------------- ### Load Scotch Whiskey data Source: https://github.com/adeverse/adespatial/blob/master/man/constr.hclust.Rd Loads the ScotchWhiskey dataset for the second example. ```R data(ScotchWhiskey) ``` -------------------------------- ### Example: beta.div.comp with ade4 doubs fish data Source: https://github.com/adeverse/adespatial/blob/master/man/beta.div.comp.Rd Loads the doubs fish data from the ade4 package and removes site 8 because no fish were caught. This prepares the community composition data for use with beta.div.comp. ```R if(require(ade4, quietly = TRUE)){ data(doubs) fish.sp = doubs$fish[-8,] # Fish data; site 8 is removed because no fish were caught ``` -------------------------------- ### forward.sel.par example with random data Source: https://github.com/adeverse/adespatial/blob/master/man/forward.sel.par.Rd Example creating random explanatory and response matrices and running forward.sel.par with alpha = 0.5. Yscale is automatically set to TRUE when Y has more than one variable, as required for the parametric test. ```r x <- matrix(rnorm(30),10,3) y <- matrix(rnorm(50),10,5) forward.sel.par(y,x, alpha = 0.5) ``` -------------------------------- ### msr example: triplet method Source: https://github.com/adeverse/adespatial/blob/master/man/msr.Rd Generates 9 replicates using the 'triplet' method and checks their Moran's I statistics. ```r ## triplet x1.2 <- msr(x1[,1], lw1, nrepet = 9, method = "triplet") apply(x1.2, 2, function(x) moran.mc(x, listw = lw1, nsim = 2)$statistic) ``` -------------------------------- ### Example: ortho.AIC usage with simulated data Source: https://github.com/adeverse/adespatial/blob/master/man/ortho.AIC.Rd Demonstrates computing corrected AIC for models with orthonormal explanatory variables. The example creates a response matrix y and orthonormal vectors x via SVD, then calls ortho.AIC with ord.var=TRUE to obtain AICc, AICc0, variable order, and cumulative R2. It compares corrected AIC with classical AIC from lm and extractAIC, and verifies the null model AICc0. ```r y <- matrix(rnorm(50),50,1) x <- svd(scale(y %*% c(0.1,0.5,2,0,0.7)+matrix(rnorm(250),50,5)))$u res <- ortho.AIC(y,x,ord.var=TRUE) minAIC <- which.min(res$AICc) nvar <- length(1:minAIC)+1 # number of orthogonal vectors + 1 for intercept lm1 <- lm(y~x[,res$ord[1:minAIC]]) summary(lm1)$r.squared # R2 res$R2[minAIC] # the same min(res$AICc) # corrected AIC extractAIC(lm1) # classical AIC min(res$AICc)-2*(nvar*(nvar+1))/(nrow(x)-nvar-1) # the same lm2 <- lm(y~1) res$AICc0 # corrected AIC for the null model extractAIC(lm2) # classical AIC res$AICc0-2*(1*(1+1))/(nrow(x)-1-1) # the same ``` -------------------------------- ### moranNP.randtest usage and example Source: https://github.com/adeverse/adespatial/blob/master/man/moranNP.randtest.Rd Computes positive and negative parts of Moran's I with permutation tests. The example requires the ade4 and spdep packages and uses the mafragh dataset. It runs a two-sided test with Holm adjustment, prints the results, compares with moran.randtest, and sums the observed statistics. ```R moranNP.randtest( x, listw, nrepet = 999, alter = c("greater", "less", "two-sided"), ... ) ``` ```R if(require("ade4", quietly = TRUE) & require("spdep", quiet = TRUE)){ data(mafragh) tests <- moranNP.randtest(mafragh$env[,1], nb2listw(mafragh$nb), alter = "two-sided", p.adjust.method = "holm") tests moran.randtest(mafragh$env[,1], nb2listw(mafragh$nb))$obs sum(tests$obs) } ``` -------------------------------- ### Compute Moran's I bounds and test MEMs with moran.bounds Source: https://github.com/adeverse/adespatial/blob/master/man/moran.bounds.Rd Example usage of moran.bounds() with spatial weighting matrices from spdep. Requires the 'ade4' and 'spdep' packages. Computes bounds for binary (B) and row-standardized (W) matrices, then runs Moran's I permutation tests on selected MEMs. ```r if(require("ade4", quietly = TRUE)){ if(require("spdep", quietly = TRUE)){ data(oribatid) nbtri <- tri2nb(as.matrix(oribatid$xy)) lwB <- nb2listw(nbtri, style = "B") lwW <- nb2listw(nbtri, style = "W") scB <- mem(lwB) scW <- mem(lwW) moran.bounds(lwB) moran.mc(scB[,1], lwB, 9) moran.mc(scB[,69], lwB, 9) moran.bounds(lwW) moran.mc(scW[,1], lwW, 9) moran.mc(scW[,69], lwW, 9) } } ``` -------------------------------- ### Example 4.3: Compute dbMEMs for irregular sites and repeat for COD.S Source: https://github.com/adeverse/adespatial/blob/master/man/stimodels.Rd Compute a matrix of dbMEMs for the irregular sites and repeat the coding matrix because COD.S must have repeated dbMEM.S codes. The snippet is incomplete in the source; only the first line is shown. ```R dbMEM.S2 <- as.matrix(dbmem(xy.trich)) ``` -------------------------------- ### Example: MSR for variation partitioning with mafragh data Source: https://github.com/adeverse/adespatial/blob/master/man/msr.varipart.Rd Performs standard variation partitioning with varipart, then adjusts estimation and computes p-values using Moran spectral randomization (MSR) with 99 replicates. Requires the ade4 and spdep packages and the mafragh dataset. ```R library(ade4) library(spdep) data(mafragh) ## Performing standard variation partitioning dudiY <- dudi.pca(mafragh$flo, scannf = FALSE, scale = FALSE) mafragh.lw <- nb2listw(mafragh$nb) me <- mem(mafragh.lw, MEM.autocor = "positive") vprda <- varipart(dudiY, mafragh$env, me, type = "parametric") ## Adjust estimation and compute p-value by msr methods vprda.msr <- msr(vprda, mafragh.lw, nrepet=99) vprda.msr ``` -------------------------------- ### msr example: pair with cor.fixed Source: https://github.com/adeverse/adespatial/blob/master/man/msr.Rd Generates 9 replicates with fixed correlation 0.5 using the 'pair' method, then checks Moran's I and correlation. ```r ## pair with cor.fixed x1.4 <- msr(x1[,1], lw1, nrepet = 9, cor.fixed = 0.5) apply(x1.4, 2, function(x) moran.mc(x, listw = lw1, nsim = 2)$statistic) cor(x1[,1], x1.4) ``` -------------------------------- ### Construct dbMEM.S10 coding matrix and run stimodels Source: https://github.com/adeverse/adespatial/blob/master/man/stimodels.Rd Builds a dbMEM.S coding matrix for 10 time points by repeating the single-time matrix 10 times, then runs stimodels with model="5" and 999 permutations. The result can be compared with the output of example 4.2 (out6). ```R dbMEM.S1 <- as.matrix(dbmem(xy.trich)) dbMEM.S10 = dbMEM.S1 for(i in 1:9) dbMEM.S10 <- rbind(dbMEM.S10, dbMEM.S1) out.7 <- stimodels(trich.log, S=22, Ti=10, model="5", COD.S=dbMEM.S10, nperm=999) ``` -------------------------------- ### msr example: singleton preserving correlations for multivariate data Source: https://github.com/adeverse/adespatial/blob/master/man/msr.Rd Joint randomization of the full matrix using the 'singleton' method, then checks correlations and Moran's I for the first replicate. ```r ## singleton preserving correlations for multivariate data x1.6 <- msr(x1, lw1, nrepet = 9, method = "singleton") cor(x1) lapply(x1.6, cor) apply(x1, 2, function(x) moran.mc(x, listw = lw1, nsim = 2)$statistic) apply(x1.6[[1]], 2, function(x) moran.mc(x, listw = lw1, nsim = 2)$statistic) ``` -------------------------------- ### Compute beta diversity with beta.div on mite data Source: https://github.com/adeverse/adespatial/blob/master/man/beta.div.Rd Example from the beta.div documentation. Requires the vegan and adegraphics packages. Computes beta diversity using the Hellinger transformation with 999 permutations. ```R if(require("vegan", quietly = TRUE) & require("adegraphics", quietly = TRUE)){ data(mite) res = beta.div(mite, "hellinger", nperm=999) ``` -------------------------------- ### Generate random coordinates and create dbMEM model Source: https://github.com/adeverse/adespatial/blob/master/man/create.dbMEM.model.Rd Creates Cartesian coordinates for 35 sites in 6 groups, defines group sizes, and calls create.dbMEM.model to build a staggered dbMEM matrix. The example then plots the sites colored by group and shows the resulting matrix (commented out). ```r { # Generate random coordinates for 35 sites forming 6 distinct groups on the map Easting <- runif(35)+c(rep(0,6),rep(1.5,7),rep(3,6), rep(0,5),rep(1.5,5),rep(3,6)) Northing<- runif(35)+c(rep(2.8,6),rep(2.3,7),rep(2.8,6), rep(0,5),rep(0.5,5),rep(0,6)) cartesian <- cbind(Easting,Northing) rownames(cartesian) <- paste("S",1:nrow(cartesian),sep='') nsites.per.group <- c(6,7,6,5,5,6) result <- create.dbMEM.model(coord=cartesian, nsites=nsites.per.group) # Draw a map to check the coding of the sites into the groups site.codes <- unlist(apply(cbind(1:6),1,n=nsites.per.group,function(a,n) rep(a,n[a]))) col.vec <- c("green3","gray99","orange2","gold1","brown3","gray70") plot(cartesian, pch=22, col="black", bg=col.vec[site.codes], cex=2, ylim=c(0,4),asp=1) text(cartesian,labels=rownames(cartesian), cex=0.5, pos=3) # Examine the staggered matrix of dbMEM eigenfunctions # Not run: result } ``` -------------------------------- ### Compute Moran's I with moran.randtest Source: https://github.com/adeverse/adespatial/blob/master/man/moran.randtest.Rd Example usage of moran.randtest on the mafragh dataset, requiring the ade4 and spdep packages. It computes Moran's I for environmental variables and plots the results. ```R if(require("ade4", quietly = TRUE) & require("spdep", quiet = TRUE)){ data(mafragh) tests <- moran.randtest(mafragh$env, nb2listw(mafragh$nb)) tests plot(tests) } ``` -------------------------------- ### Run multispati on mafragh data with ade4 and spdep Source: https://github.com/adeverse/adespatial/blob/master/man/multispati.Rd Loads the mafragh dataset, creates a spatial weights list, performs a correspondence analysis, and applies multispati with two positive and two negative axes. Requires the spdep and ade4 packages. The example includes conditional graphics handling for adegraphics. ```R if (require(spdep, quiet = TRUE) & require(ade4, quiet = TRUE)) { data(mafragh) maf.xy <- mafragh$xy maf.flo <- mafragh$flo maf.listw <- nb2listw(mafragh$nb) if(adegraphicsLoaded()) { g1 <- s.label(maf.xy, nb = mafragh$nb, plab.cex = 0.75) } else { s.label(maf.xy, neig = mafragh$neig, clab = 0.75) } maf.coa <- dudi.coa(maf.flo,scannf = FALSE) maf.coa.ms <- multispati(maf.coa, maf.listw, scannf = FALSE, nfposi = 2, nfnega = 2) maf.coa.ms ``` -------------------------------- ### Constrained clustering on 6 connected points with custom edges Source: https://github.com/adeverse/adespatial/blob/master/man/constr.hclust.Rd Creates a small example with 6 points, their coordinates, and a matrix of connecting edges. Runs constr.hclust with Ward.D2 method and the given links, then plots the map for k=3 and the dendrogram. ```R var = c(1.5, 0.2, 5.1, 3.0, 2.1, 1.4) ex.Y = data.frame(var) ``` ```R x.coo = c(-1, -2, -0.5, 0.5, 2, 1) y.coo = c(-2, -1, 0, 0, 1, 2) ex.xy = data.frame(x.coo, y.coo) ``` ```R from = c(1,1,2,3,4,3,4) to = c(2,3,3,4,5,6,6) ex.E = data.frame(from, to) ``` ```R test.out <- constr.hclust( dist(ex.Y), # Response dissimilarity matrix method="ward.D2", # Clustering method links=ex.E, # File of link edges (constraint) E coords=ex.xy # File of geographic coordinates ) ``` ```R par(mfrow=c(1,2)) ## Plot the map of the results for k = 3 plot(test.out, k=3) ## Plot the dendrogram stats:::plot.hclust(test.out, hang=-1) ``` -------------------------------- ### Run TBI on mite data (Example 2) Source: https://github.com/adeverse/adespatial/blob/master/man/TBI.Rd Loads the mite dataset from vegan, treats sites 1-20 as T1 and sites 21-40 as T2, runs the TBI function with method '%diff', nperm = 0, and test.t.perm = FALSE. Prints summary and BCD matrix. ```R data(mite) ``` ```R res2 <- TBI(mite[1:20,], mite[21:40,], method = "%diff", nperm = 0, test.t.perm = FALSE) ``` ```R summary(res2) ``` ```R res2$BCD.mat ``` -------------------------------- ### Example 4.2: Provide irregular site coordinates to S argument Source: https://github.com/adeverse/adespatial/blob/master/man/stimodels.Rd Create a matrix of geographic coordinates for irregularly positioned sites and pass it to stimodels via the S argument. Includes a quick plot of the site positions. ```R xy.trich = matrix(c(1:5,11:15,21:25,31:35,41,42,rep(c(1,2),11)),22,2) plot(xy.trich, asp=1) # Plot a quick map of the site positions out.6 <- stimodels(trich.log, S=xy.trich, Ti=10, model="5", nperm=999) ``` -------------------------------- ### Run TBI on mite data Source: https://github.com/adeverse/adespatial/blob/master/man/plot.TBI.Rd Example 2: Uses the mite data from vegan. Pretends sites 1-20 are survey at time 1 and sites 21-40 at time 2. Runs TBI with method="%diff", nperm=0, and test.t.perm=FALSE, then displays the BCD matrix. ```R data(mite) ``` ```R res2 <- TBI(mite[1:20,],mite[21:40,],method="\%diff",nperm=0,test.t.perm=FALSE) ``` ```R res2$BCD.mat ``` -------------------------------- ### Example 3: Baselga-family partitioning with beta.div.comp and beta.pair.abund Source: https://github.com/adeverse/adespatial/blob/master/man/LCBD.comp.Rd Requires packages 'betapart' and 'ade4'. Uses abundance data from the Doubs dataset (site 8 removed). Partitions %difference dissimilarity into replacement and nestedness components using beta.div.comp with coef='BS' and quant=TRUE, then computes D and component matrices using beta.pair.abund with index.family='bray'. The D matrix is not Euclidean, so sqrt.D=TRUE is used in LCBD.comp. ```R if(require("ade4", quietly = TRUE) & require("betapart", quietly = TRUE)){ ``` ```R data(doubs) # Data available in \code{"ade4"} fish.sp = doubs$fish[-8,] # Fish data; site 8 is removed because no fish were caught # We use abundance data in this example, not presence-absence data ``` ```R # Partition into Baselga-family replacement and nestedness components # using \code{"beta.div.comp"} with the percentage difference index (aka Bray-Curtis) out.comp = beta.div.comp(fish.sp, coef="BS", quant=TRUE) out.comp$part ``` ```R # Compute the D and component matrices using \code{"beta.pair.abund"} out3 = beta.pair.abund(fish.sp, index.family = "bray") summary(out3) ``` ```R is.euclid(out3$beta.bray) # D matrix out3$beta.bray is not Euclidean out3.D = LCBD.comp(out3$beta.bray, sqrt.D=TRUE) out3.D$beta ``` -------------------------------- ### Run space-time analysis with global tests (Example 2) Source: https://github.com/adeverse/adespatial/blob/master/man/stimodels.Rd Runs quicksti on trich.log with S=22, Ti=10, and 999 permutations. Since the interaction is significant, the function performs global tests for spatial and temporal structures using models 6a and 6b. ```R out.2 <- quicksti(trich.log, S=22, Ti=10, nperm=999) ``` -------------------------------- ### give.thresh usage example Source: https://github.com/adeverse/adespatial/blob/master/man/give.thresh.Rd Computes the truncation threshold for dbMEM from a distance matrix. The example creates random coordinates, computes a distance matrix, and calls give.thresh to get the maximum distance in the minimum spanning tree. ```r xy <- matrix(rnorm(60),30,2) dxy <- dist(xy) th <- give.thresh(dxy) ``` -------------------------------- ### Time series example using aem.weight.time Source: https://github.com/adeverse/adespatial/blob/master/man/aem.weight.edges.Rd Example with 12 dates from a 6-year study starting September 5, 2000. Requires the spdep package. The autocor.limit value (522) is used as max.d, representing the limit of autocorrelation in the correlogram. ```R if(require("spdep", quietly = TRUE)){ dates <- as.Date(c(129,269,500,631,864,976,1228,1352,1606,1730,1957,2087),origin="2000/1/1") autocor.limit <- 522 # Limit of autcorrelation in the correlogram ### Using aem.weight.time() (wtime <- aem.weight.time(dates, alpha=2, max.d=autocor.limit)) } ``` -------------------------------- ### Run TBI on pyrifos data (Example 1) Source: https://github.com/adeverse/adespatial/blob/master/man/TBI.Rd Loads the pyrifos dataset, selects rows for surveys 4 and 11, reorders them by insecticide dose, and runs the TBI function with method '%diff', nperm = 0, and test.t.perm = FALSE. Prints the BCD matrix. ```R data(pyrifos) ``` ```R ord4 = c(38,39,41,47,37,44,40,46,43,48,42,45) ``` ```R ord11 = c(122,123,125,131,121,128,124,130,127,132,126,129) ``` ```R res1 <- TBI(pyrifos[ord4,], pyrifos[ord11,], method = "%diff", nperm = 0, test.t.perm = FALSE) ``` ```R res1$BCD.mat ``` -------------------------------- ### Example 2: Compute LCBD from beta diversity components Source: https://github.com/adeverse/adespatial/blob/master/man/LCBD.comp.Rd Computes LCBD from beta diversity components (replacement, richness difference) for fish data. Requires ade4 and adegraphics. Uses beta.div.comp with coef="S", quant=TRUE. Shows different sqrt.D settings for each component. Includes plotting maps of LCBD indices. ```R if(require("ade4", quietly = TRUE) & require("adegraphics", quietly = TRUE)){ data(doubs) fish.sp = doubs$fish[-8,] # Fish data; site 8 is removed because no fish were caught out.comp = beta.div.comp(fish.sp, coef="S", quant=TRUE) out.fish.D = LCBD.comp(out.comp$D, sqrt.D=TRUE) # out.comp.D is not Euclidean out.fish.D$beta out.fish.Repl = LCBD.comp(out.comp$repl, sqrt.D=TRUE) # out.comp$repl is not Euclidean out.fish.Repl$beta out.fish.AbDiff = LCBD.comp(out.comp$rich, sqrt.D=FALSE) # out.comp$rich is Euclidean out.fish.AbDiff$beta ### Plot maps of the LCBD indices fish.xy = doubs$xy[-8,] # Geographic coordinates; site 8 removed because no fish were caught } ``` -------------------------------- ### Construct AEM eigenfunctions with distance-based weights Source: https://github.com/adeverse/adespatial/blob/master/man/aem.Rd Builds AEM eigenfunctions from a binary site-by-link matrix using weights based on the distance between sites. Requires spdep's cell2nb to create a neighborhood object and aem.build.binary to generate the binary matrix. The example creates a 5x5 queen neighborhood, computes edge lengths from coordinates, and applies a weight vector before calling aem with rm.link0=TRUE. ```R nb<-cell2nb(5,5,"queen") ``` ```R xy <- cbind(1:25,expand.grid(1:5,1:5)) ``` ```R bin.mat <- aem.build.binary(nb,xy) ``` ```R long.lien.mat<-as.matrix(dist(xy)) ``` ```R lien.b<-bin.mat$edges[-1:-5,] ``` ```R long.lien<-vector(length=nrow(lien.b)) for(i in 1:nrow(lien.b)){ long.lien[i]<-long.lien.mat[lien.b[i,1],lien.b[i,2]] } ``` ```R weight.vec<-1-(long.lien/max(long.lien))^2 ``` ```R res <- aem(aem.build.binary=bin.mat,weight=weight.vec,rm.link0=TRUE) res ``` -------------------------------- ### aem.build.binary Source: https://github.com/adeverse/adespatial/blob/master/man/aem.build.binary.Rd Constructs a binary site-by-edge matrix from site coordinates and a connexion diagram. It returns the binary matrix and the list of edges, including links to a fictitious upstream site. ```APIDOC ## aem.build.binary ### Description Constructs a binary site-by-edge matrix from site coordinates and a connexion diagram. It returns the binary matrix and the list of edges, including links to a fictitious upstream site. ### Usage ```r aem.build.binary( nb.object = NULL, coords, link = NULL, unit.angle = "degrees", rot.angle = 0, rm.same.y = TRUE, plot.connexions = TRUE ) ``` ### Parameters #### nb.object - **nb.object** (object of class `nb` from library spdep) - Optional - Object of class `nb` from library spdep. #### coords - **coords** (matrix or data frame) - Required - A three columns matrix or data frame. Colums 1: identifiers of the points (needs to be numeric). Columns 2 and 3: the X and Y coordinates of the points. #### link - **link** (matrix) - Optional - A two columns matrix. Each row define an edge. Column 1: The site from which the edge starts. Column 2: the site to which the edge ends. All values in `link` need to be integers. #### unit.angle - **unit.angle** (character) - Optional - The measurement units in which the angle is defined: either "degrees" (default) or "radians". #### rot.angle - **rot.angle** (numeric) - Optional - Angle of the vector describing the process influencing the sites. This argument generate a rotation of the site coordinates. The set of coordinates is rotated counterclockwise. Negative values will produce a clockwise rotation. #### rm.same.y - **rm.same.y** (logical) - Optional - Determines if the links perpendicular to the gradient should be removed. Default value: `TRUE`. If these links have already been removed this argument put to `TRUE` will make the function crash. See detail for more information. #### plot.connexions - **plot.connexions** (logical) - Optional - Determines if the sites and the associated connexion diagram should be plotted after rotation of the coordinates by `gradient.angle`. ### Value - **se.mat** (binary matrix) - A binary (n x k) matrix of site (n rows) by link edges (k columns). - **edges** (matrix) - A matrix describing the link edges. It has 2 columns (from, to) and as many rows as there are edges. The edges linked to the fictitious site of origin are found at the beginning of the list. ### Examples ```r ### Create an object of class nb (spdep) if(require("spdep", quietly = TRUE)){ nb<-cell2nb(5,5,"queen") ### Create fictitious geographical coordinates xy <- cbind(1:25,expand.grid(1:5,1:5)) ### Build a binary site-by-link matrix; remove the site which have identical Y coordinate ### (by default argument: rm.same.y = TRUE) bin.mat <- aem.build.binary(nb,xy) str(bin.mat) ### Build a binary site-by-link matrix using the argument link: remove the site which ### have identical Y coordinate (by default argument: rm.same.y = TRUE) edges<-expand.grid(1,2:25) bin.mat <- aem.build.binary(coords=xy,link=edges) str(bin.mat) ``` ``` -------------------------------- ### Run listw.explore() interactively Source: https://github.com/adeverse/adespatial/blob/master/man/listw.explore.Rd Launches an interactive tool that generates R code for creating a spatial weighting matrix. Requires a matrix or Spatial* object in the global environment. Only runs in interactive R sessions. ```R if(interactive()){ ## a matrix or an object of class 'Spatial*' should be in the global environment xy <- matrix(rnorm(50), 25) listw.explore() } ``` -------------------------------- ### Example: Deer leg length data and test Source: https://github.com/adeverse/adespatial/blob/master/man/tpaired.randtest.Rd Example using deer leg length data from Zar (1999). Creates a matrix, sets row and column names, then runs tpaired.randtest with default two-tailed test. Comments show comparison to t.test. ```r ## Deer leg length, data from Zar (1999, p. 162). deer <- matrix(c(142,140,144,144,142,146,149,150,142,148,138,136,147,139,143,141,143, 145,136,146),10,2) rownames(deer) <- paste("Deer",1:10,sep=".") colnames(deer) <- c('Hind.leg', 'Fore.leg') res <- tpaired.randtest(deer[,1], deer[,2]) # Two-tailed test by default ## Compare the results to: res2 = t.test(deer[,1], deer[,2], paired=TRUE) ``` -------------------------------- ### Example: Compute MEMs with scores.listw and plot Source: https://github.com/adeverse/adespatial/blob/master/man/mem.Rd Example from the documentation. Requires the ade4 and spdep packages. Computes MEMs from a triangulated neighbor list on the oribatid dataset, then plots the first six MEMs using adegraphics. ```R if(require("ade4", quietly = TRUE) & require("spdep", quietly = TRUE)){ data(oribatid) nbtri <- tri2nb(as.matrix(oribatid$xy)) sc.tri <- scores.listw(nb2listw(nbtri, style = "B")) summary(sc.tri) } if(require("adegraphics", quietly = TRUE)){ s.value(oribatid$xy,sc.tri[,1:9]) plot(sc.tri[,1:6], oribatid$xy, pSp.cex = 5, pSp.alpha = 0.5, pbackground.col = 'lightblue') } ``` -------------------------------- ### Temporal example with rot.angle=90: aem.weight.edges() Source: https://github.com/adeverse/adespatial/blob/master/man/aem.weight.edges.Rd Alternative temporal weighting that rotates the coordinate system by 90 degrees, inverting the 'dates' and 'rep(1,n)' columns in 'xy.dates'. Requires 'dates' and 'autocor.limit' from a prior example. The result is assigned to 'wtime' and printed. ```R n <- length(dates) nb <- cell2nb(1, n) xy.dates <- cbind(1:n, dates, rep(1, n)) ## Note the inversion of 'dates' and 'rep(1,n)' wtime <- aem.weight.edges(nb, xy.dates, alpha=2, max.d=autocor.limit,rot.angle=90) # Note that 'rot.angle=90' was used ``` -------------------------------- ### Display selection results Source: https://github.com/adeverse/adespatial/blob/master/man/envspace.test.Rd Shows the best SWM name, adjusted p-value, number of selected MEM variables, and adjusted R-squared. ```R names(candidates)[modsel.Y$best.id] # Best SWM selected modsel.Y$candidates$Pvalue[modsel.Y$best.id] # Adjusted p-value of the global model modsel.Y$candidates$N.var[modsel.Y$best.id] # Nb of forward-selected MEM variables modsel.Y$candidates$R2Adj.select[modsel.Y$best.id] # Adjusted R2 of the selected MEM var. ``` -------------------------------- ### Build binary matrix from nb object (spdep) Source: https://github.com/adeverse/adespatial/blob/master/man/aem.build.binary.Rd Creates a site-by-edge binary matrix using a queen contiguity nb object and coordinates. Requires the spdep package. The default rm.same.y=TRUE removes links perpendicular to the gradient. ```R if(require("spdep", quietly = TRUE)){ nb<-cell2nb(5,5,"queen") ### Create fictitious geographical coordinates xy <- cbind(1:25,expand.grid(1:5,1:5)) ### Build a binary site-by-link matrix; remove the site which have identical Y coordinate ### (by default argument: rm.same.y = TRUE) bin.mat <- aem.build.binary(nb,xy) str(bin.mat) ``` -------------------------------- ### Select best SWM for env using listw.select Source: https://github.com/adeverse/adespatial/blob/master/man/envspace.test.Rd Runs listw.select with method = "global" to optimize the spatial weighting matrix for the env data, using all MEM variables as required for MSR. The result is stored in modsel.env. ```R modsel.env <- listw.select(env, candidates, method = "global", MEM.autocor = "positive", p.adjust = TRUE) ``` -------------------------------- ### Build candidate SWMs Source: https://github.com/adeverse/adespatial/blob/master/man/envspace.test.Rd Creates five candidate spatial weighting matrices (SWMs) using Gabriel graph, minimum spanning tree, and PCNM, with binary or linear distance weighting. ```R candidates <- listw.candidates(coord, nb = c("gab", "mst", "pcnm"), weights = c("binary", "flin")) ``` -------------------------------- ### Run with more permutations Source: https://github.com/adeverse/adespatial/blob/master/man/tpaired.krandtest.Rd Runs tpaired.krandtest on species 15-19 with nperm=9999 for a more precise p-value estimate. This code is not run in the example. ```R res2 <- tpaired.krandtest(mat1[,15:19], mat2[,15:19], nperm=9999, opt=2) ``` -------------------------------- ### Load required packages for adespatial analysis Source: https://github.com/adeverse/adespatial/blob/master/vignettes/tutorial.Rmd Loads the packages needed to run the analyses described in the vignette: ade4, adespatial, adegraphics, spdep, and sp. ```r library(ade4) library(adespatial) library(adegraphics) library(spdep) library(sp) ``` -------------------------------- ### listw.explore() Source: https://github.com/adeverse/adespatial/blob/master/man/listw.explore.Rd Interactive tool to generate R code that creates a spatial weighting matrix. It requires a matrix or an object of class 'Spatial*' in the global environment. ```APIDOC ## listw.explore() ### Description Interactive tool to generate R code that creates a spatial weighting matrix. ### Usage listw.explore() ### Arguments None. ### Value No return value. ### Examples ```r if(interactive()){ ## a matrix or an object of class 'Spatial*' should be in the global environment xy <- matrix(rnorm(50), 25) listw.explore() } ``` ### See Also [chooseCN] ``` -------------------------------- ### Example: load oribatid data Source: https://github.com/adeverse/adespatial/blob/master/man/dbmem.Rd Loads the oribatid mite data from the ade4 package and extracts the species abundance matrix and geographic coordinates. Requires the ade4 and adegraphics packages. ```r if(require("ade4", quietly = TRUE) & require("adegraphics", quietly = TRUE)){ data(oribatid) mite <- oribatid$fau # 70 peat cores, 35 species mite.xy <- oribatid$xy # Geographic coordinates of the 70 cores } ``` -------------------------------- ### Prepare data for SSEF test Source: https://github.com/adeverse/adespatial/blob/master/man/envspace.test.Rd Loads the mite community data, applies Hellinger transformation, selects two environmental variables, and loads site coordinates. ```R data(mite) Y <- decostand(mite, method = "hellinger") data(mite.env) env <- mite.env[, 1:2] dim(Y) dim(env) data(mite.xy) coord <- mite.xy ```