Search code examples
rrasterquantile

Incorrect local quantiles with the raster package's focal function


I am trying to calculate local quantiles with the raster R package. But am not able to generate sensible results.

This is a minimal example that produces the odd results:

library(raster)

set.seed(100)
n <- 5

# create a raster object
r <- raster::raster( matrix(rnorm(n^2),n,n)) 

# create a weight matrix
W <- matrix(1,nrow=3,ncol=3)

# create a weight matrix
rLocalKDE2 <- raster::focal(r,W,fun=stats::quantile,probs=0.3)

The as.matrix function of the two raster images produces:

 > as.matrix(r)
      [,1]       [,2]       [,3]       [,4]      [,5]
 [1,]  1.449469 19.5963292 -2.4142891 -1.7028303 -8.851035
 [2,]  1.049408 -0.6686213 -0.3880794  0.7489177 -1.282491
 [3,] -6.028731  2.3172630  1.2115319  2.0829121 -8.260212
 [4,]  0.179009 -6.7879331  3.0286532  2.1160440 -1.006479
 [5,] 10.087954  0.5925101 -0.9240929 -1.4685703  3.899903

 > as.matrix(rLocalKDE2)
       [,1]      [,2]      [,3]      [,4] [,5]
 [1,]   NA        NA        NA        NA   NA
 [2,]   NA -6.028731 -2.414289 -8.851035   NA
 [3,]   NA -6.787933 -6.787933 -8.260212   NA
 [4,]   NA -6.787933 -6.787933 -8.260212   NA
 [5,]   NA        NA        NA        NA   NA

This result seems quite odd, given that stats::quantile(as.matrix(r)[2:4,2:4],probs=0.3) returns 0.06671944.

I am running R 3.3.1 from brew on OS X 10.11.6 with raster 2.5-8.


Solution

  • Your formulation of the function is not correct, as the probs argument is defined outside the function and passed on as additional argument to focal and ignored. In effect you got the 0 percentile returned. See below for a corrected version:

    library(raster)
    
    set.seed(100)
    n <- 5
    r <- raster::raster( matrix(rnorm(n^2),n,n)) 
    W <- matrix(1,nrow=3,ncol=3)
    
    # create a weight matrix
    k <- raster::focal(r, W, fun=function(x) stats::quantile(x,probs=0.3))
    
    as.matrix(k)
         [,1]       [,2]       [,3]        [,4] [,5]
    [1,]   NA         NA         NA          NA   NA
    [2,]   NA -0.1525472 -0.1327071 -0.13270706   NA
    [3,]   NA -0.1525472 -0.5046161 -0.08247059   NA
    [4,]   NA -0.1525472 -0.2965709 -0.07162857   NA
    [5,]   NA         NA         NA          NA   NA
    >