R – How to Calculate the Lower 5th Percentile for Raster TIF

geotiff-tiffrraster

I have a tif file of the lowest temperature measured the last 21 years (21 bands of floats) over Europe. I would like to calculate the lower 5th percentile value for each pixel and create a new tif file consisting of one band with the lowest 5th percentile. I know how to calculate the mean and the median for the pixels with calc, but I do not know how to do it for the 5th percentile.
Here is the script

library(raster)
stacked <- stack("D:/snowmelt/snowmelt/daily/googledeveloper/new/temp_EU.tif")
stacked.mean <- calc(stacked, fun = mean)
stacked.median <- calc(stacked, fun = median)
stacked.lowperc <-calc(stacked, fun = quantile(0.05)) #This does not work

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘calc’ for signature ‘"RasterStack", "numeric"

The last part of the script does not yield a map of the lower 5th percentile.
How can I do that?

Best Answer

Quantile asks for 2 arguments, namely the stacker raster, x in this case and the probability (0.05 and 0.95 in the example below)

calc(s, fun = function(x) {quantile(x, probs = c(.05,.95),na.rm=TRUE)} )