I have a Raster Stack with 32 Raster Layers. What I want to do is to calculate the median for each Raster and also the 0.25 and 0.75 quantiles. Then I want to convert the results into a dataframe.

For the median I have allready found a quite simple solution:

#calculate median and convert to dataframe

median.df <- data.frame(cellStats(r_stack, "median"))

The Problem is, that I can´t do the same with the quantiles, since cellStats cant calculate that.

My best approach with the quantiles so far was:

quant <- calc(r_stack, fun = function(x) 
          {quantile(x,probs = c(.25,.75),na.rm=TRUE)} )

quant.df <- as.data.frame(quant)

But the dataframe has 16644 rows instead of the expected 32.

1 Answer 1


You can supply a function to cellStats - here on a 5 layer example:

> cellStats(r_stack, function(s,...){quantile(s,probs=c(.25,.75))})
      layer.1   layer.2   layer.3   layer.4   layer.5
25% 0.3613589 0.2072302 0.3314491 0.3160375 0.1740109
75% 0.8063743 0.8571872 0.8297163 0.6712669 0.7010024

that's a matrix but save that as m and a quick flip to a dataframe is easy enough:

> data.frame(t(m))
             X25.      X75.
layer.1 0.3613589 0.8063743
layer.2 0.2072302 0.8571872
layer.3 0.3314491 0.8297163
layer.4 0.3160375 0.6712669
layer.5 0.1740109 0.7010024

quick check, this should match the third row:

> quantile(r_stack[[3]],probs=c(.25,.75))
      25%       75% 
0.3314491 0.8297163 
  • Thank you very much Spacedman! The code works for me after I added na.rm=TRUE in the quantile function. Commented Sep 17, 2018 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.