0
votes

I have a large raster data set (several actually). I'm looking for a moving window process for R (like 'focal' in the raster package). However, the function to apply to the window needs to be caclulated relative to the center cell of said window.

For a simple example, I would like a moving window function that tells me how many of the cells in the window are within some value 'd' of the center cell of the window. I suspect I could do this easily by simply querying the value of the center cell and writing a function around it to use in focal(). However, I'm not sure how to query that center cell of the window.

If that's possible, then I will eventually need to run this function on one raster based on the value of the center cell in another perfectly overlaid raster (which could be in a stack or something).

I'm comfortable with raster work, but not that familiar with the focal() command from the {raster} package in R. Hoping someone can provide some info.

1
Would you mind to provide further details about "how many of the cells in the window are within some value 'd' of the center cell of the window"? what you have done so far?Paulo E. Cardoso
Sorry Paulo, didn't mean to be vague. I just gave that example as a very simple calculation that might be done around the centre cell of the focal window. In reality, I need to introduce a much more complicated function, but that seemed beside the point here.David Roberts
it may be easy to adapt the focal function to read the reference "d" data from another rasterLayer.Paulo E. Cardoso

1 Answers

3
votes
library(raster)
# taking a 4x5 matrix as a simple example.
x <- matrix(1:20, 4)
> x
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20
# convert it to a rasterLayer
r <- raster(x)
d <- 15 # a value to use as reference with the function
# a criterion function to apply with focal (moving window)
f.rast <- function(x) length(x[x>d]) 
# apply the function to a 3x3 moving window
aggr <- as.matrix(focal(r, matrix(1,3,3), f.rast, pad = T, padValue = 0))
> aggr
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    2    2
[2,]    0    0    0    3    3
[3,]    0    0    1    4    4
[4,]    0    0    1    3    3

now I think it as a matter of understanding your filter "d".