I am trying to standardise a raster file by removing the values exceeding the mean +/- 2.5 std calculated for each polygon of a shapefile. I manage to calculate the zonal statistics and feed them back into the shapefile, but am unable to mask my raster file with the data included in the shapefile. I get an error message running the last two lines of code. Extracting the values above mean + 2.5 std gives me only a value (NA), rather than a raster as output and as a result the mask function gives the following error:
Error in (function (classes, fdef, mtable): unable to find an inherited method for function ‘mask’ for signature ‘"RasterBrick", "logical"’
#Read raster file
library(raster)
prec <- getData('worldclim', var='prec', res=10)
#Read shapefile
france <- getData('GADM', country='FRA', level=1)
#Convert shapefile to raster
r_fra <- rasterize(france, prec)
#Calculate mean for each polygon
mean_fra_prec <- zonal(prec, r_fra, FUN='mean')
#Calculate standard deviation for each polygon
std_fra_prec <- zonal(prec, r_fra, FUN = 'sd')
#Calculate mean +/- 2.5 std for each polygon
ul_prec <- mean_fra_prec + (2.5 * std_fra_prec)
ll_prec <- mean_fra_prec - (2.5*std_fra_prec)
#Merge mean +/- 2.5 std for each polygon
x <- data.frame(zone=1:22)
ul_prec2 <- merge(x, ul_prec, by='zone', all.x=TRUE)
ll_prec2 <- merge(x, ul_prec, by='zone', all.x=TRUE)
#Join new data to shapefile
france@data <- cbind(france@data, ul_prec2[,-1])
france@data <- cbind(france@data, ll_prec2[,-1])
#Remove values above mean + 2.5 std for each polygon
ext_prec <- prec[!(prec > france@data$ul_prec2)] <- NA #Values above mean + 2.5 std
ma_prec <- mask(prec, ext_prec) #Mask values above mean + 2.5 std
rastr = raster(volcano)from raster package? - geotheory