[R-sig-Geo] Moving window correlation

Jaime R. Garcia M. jaime.garcia at uni-bonn.de
Tue Dec 8 21:54:35 CET 2009

On Tue, 2009-12-08 at 14:32 -0500, Zia Ahmed wrote:
> I have two grid maps (100 m cell size). I want to a create another  
> raster gird  of  correlation  coefficient ( r value) of  two maps using  
> moving windows approach.  Has someone  any idea how to do it in R?
> Thanks
> Zia
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Dear Zia,

Some time ago I did exactly that and the script was based on a earlier
post by Prof. Roger Bivand in this list. (Sorry I couldn't find the link

Suppose "G1" and "G2" are the two grid maps.
I assume they are "SpatialGridDataFrames" and have exactly the same
extent and number of columns and rows. Also that you have libraries (sp)
and (spdep) loaded

# Define the size of the moving window, for example (7*7) so you have
enough neighbors for reliable correlation estimation:

dist = sqrt(2*((100*3)^2))

# Create a list of neighbours for the distance criteria
nb <- dnearneigh(coordinates(G1),0, dist) 

# And then calculate correlations
v <- sapply(nb, function(i) cor(G1 at data, G2 at data))

# The result should be a matrix if I am not wrong, so I did transpose it
and converted it to a data frame

v = as.data.frame(t(v))

# And finally I created a new grid map:
coordinates(v) = coordinates(G1)
gridded(v) = TRUE
fullgrid(v) = TRUE

I did not run the script above...

Hope this helps,

Jaime -R.

More information about the R-sig-Geo mailing list