Effective window movement statistics for matrix and / or spatial data (neighborhood statistics) in R

I use raster and related packages in R to work a bit with remote sensing. For a number of functions that I write, I would like to quickly calculate the statistics of neighborhoods / moving windows. Unfortunately, any R-implementations I or other entries are very, very slow.

I know that the caTools package offers this functionality written in C for vectors / time series, which gives 10x + time savings. Is anyone familiar with a similar package or function that provides this functionality for matrices and spatial data?

Quick example:

# Generate a raster with random values r <- raster(nrows=100, ncols=100) values(r) <- rbinom(dim(r)[1] * dim(r)[2], 1, 0.1) # Now generate a raster highlighting the original values plus immediate neighbors # (By default ngb yields a queen-esque weighting system) r.neighbor <- focal(r, ngb=3, fun=max) # system.time() of the above function for a 100x100 raster takes 0.8 seconds on my laptop # and takes over 15 seconds for a 1000x1000 raster 

Ideally, I would like to do it faster and for much larger rasters.

Thanks a lot Nick

Ps. There is an interesting discussion of massive velocity differences in R-functions for performing operations with windows on vectors here: http://tolstoy.newcastle.edu.au/R/help/04/10/5161.html

+4
source share

All Articles