I am trying to find out the number of species per polygon within an area (America) and store this result in a table where the number of columns is the total number of species in America, and the number of rows is the total number of polygons within that area.
For this I am trying to create first an empty matrix where the results will be stored and then create a loop through all the layers (202) in a RasterBrick file called in this example “SDM.b” (each layer = distribution species (x) ), and compute zonal statistics on the raster “regionRas” which stores polygons in which I divided my area of interest. Those polygons are called “Distritos” in the raster “regionRas” and have a unique code called “CODIGO” in the raster “regionRas” please see this pic for info about those rasters.
This is the code I have:
library(maptools)
library(sp)
library(geosphere)
library(raster)
#this is the empty matrix
SpeciesRegions <- matrix(NA, nrow=87, ncol=nlayers(SDM.b))
#here I am trying to fill that matrix
for(i in 1:nlayers(SDM.b))
{
SpeciesRegions[,i] <- zonal(clipped.spp.diversity.mask, regionsRas,fun='sum',digits=0, na.rm=TRUE)[,1]
}
#convert the matrix data to logical (true/false) data
SpeciesRegions <- SpeciesRegions > 0
The intended output will look something like this:
species 1 species 2 species 3
polygon 1 FALSE TRUE TRUE
polygon 2 TRUE FALSE FALSE
polygon 3 FALSE TRUE TRUE
but this is the error I am getting in the loop
“Error in SpeciesRegions[, i] <- zonal(clipped.spp.diversity.mask, regionsRas, :
number of items to replace is not a multiple of replacement length”
I would appreciate any help...