1

I'm using the function focal_hpc from spatial.tools in R to compute for each cell of a raster the average value (mean function) around windows of a specific size (3 cells x 3 cells).

I used to perform this analysis using the similar function focal, which is however slower than focal_hpc when using large raster files.

The advantage of focal is that the user can specify a matrix of weights. However, focal_hpc does not seem to provide this option.

I have been trying to use a custom function, such as:

f_mean = function(x,weight_pix){
  x[is.na(x)]<-0
  weighted.mean(x,weight_pix)
}

However, I keep getting this error, which I do not really understand:

Error in weight_pix * x : non-conformable arrays

Do you have any suggestion?

1
  • The help indicates that the rasterEngine function should be used in leu of focal_hpc. That aside, help states " the input can be passed to the function as an array". Your current function is operating on a vector. You may be able to simply coerce the x matrix/array to a vector as the first step in your function. I commonly do this in raster::focal functions. Sep 30, 2020 at 18:19

1 Answer 1

0

to apply a focal or moving window to your raster cells I can suggest two option, but I don't know if that's what you asked, and which one is faster ^^

The first one from the package raster :

f_mean = focal(x, w=matrix(1,3,3), fun = mean) #x (your raster) ; w= here a matrix 3*3 with value of 1

Second one from package mmand, that I prefere

library(mmand)
Kernel = shapeKernel(c(3,3), type="box") # you can set the size of the window (or kernel), and shape of it!
tmp = meanFilter(as.matrix(r), Kernel) #you can use medianfilter as well
f_mean = setValues(r,tmp)

I like the package mmand, there are some other options, like gaussian filters, or morphological operation (opening, closing, etc)

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.