# [R-sig-Geo] Moving window correlation

Jaime R. Garcia M. jaime.garcia at uni-bonn.de
Wed Dec 9 03:21:29 CET 2009

```On Tue, 2009-12-08 at 21:54 +0100, Jaime R. Garcia M. wrote:
> 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
> anymore)
>
> 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)
>
> # 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))

# Small correction

v = sapply(nb, function(i) cor(G1 at data[i,], G2 at data[i,]))

#  And in this case the result should be a numeric vector

coordinates(v) = coordinates(G1)
gridded(v) = TRUE
fullgrid(v) = TRUE
_______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

```