Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sliding window function in R

Does somebody know whether there is a sliding window method in R for 2d matrices and not just vectors. I need to apply median function to an image stored in matrix

like image 763
Sergej Andrejev Avatar asked Oct 20 '25 09:10

Sergej Andrejev


1 Answers

The function focal() in the excellent raster package is good for this. It takes several arguments beyond those shown in the example below, and can be used to specify a non-rectangular sliding window if that's needed.

library(raster)

## Create some example data
m <- matrix(1, ncol=10, nrow=10)
diag(m) <- 2
r <- as(m, "RasterLayer") # Coerce matrix to RasterLayer object

## Apply a function that returns a single value when passed values of cells
## in a 3-by-3 window surrounding each focal cell 
rmean <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=mean)
rmedian <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=median)

## Plot the results to confirm that this behaves as you'd expect
par(mfcol=c(1,3))
plot(r)
plot(rmean)
plot(rmedian)

## Coerce results back to a matrix, if you so desire
mmean <- as(rmean, "matrix")

enter image description here

like image 129
Josh O'Brien Avatar answered Oct 21 '25 23:10

Josh O'Brien