David Roberts
David Roberts

Reputation: 627

R focal (raster package) function that calculates relative to center cell of moving window

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.

Upvotes: 0

Views: 3154

Answers (1)

Paulo E. Cardoso
Paulo E. Cardoso

Reputation: 5856

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".

Upvotes: 3

Related Questions