[R-sig-Geo] Moving-window sum in a matrix

Stephane DRAY dray at biomserv.univ-lyon1.fr
Thu Dec 16 16:29:32 CET 2004


Hello,
I think that you could do it using spdep package. I suppose that, if you:
- construct a neighborhoord object (nb class). You can define a distance 
based neighborhood (using dnearneigh) as it seems that your definition is 
similar to say i and j neighbors if 0<dij<sqrt(cellsize^2+(2*cellsize)^2)
- then transform the nb to listw with nb2listw with style="B"
- then use lag.listw to sompute the sum

an example:
 > myvalues=rbinom(100,size=1,prob=0.5)
 > xy=expand.grid(1:10,1:10)
 > dnn1=dnearneigh(as.matrix(xy),0,sqrt(1+4))
 > plot(dnn1,as.matrix(xy))
 > nb2listw(dnn1,style="B")
 > lw1=nb2listw(dnn1,style="B")
 > sum.neigh=lag.listw(lw1,myvalues)
 > sum.neigh
   [1]  3  6  4  5  7  5  4  4  3  3  6  8  6  7  9  8  6  8  6  4  5  9 10 
11 10  7  8  9  7  5
  [31]  7 10 14 11 10  8  8  9  8  5  8 12 11 10 11 12 10 12 11  7  9 11 
12  9 13 11 10 12 12  9
  [61]  6 11 12 13 10 12 10 13  9  7  6  9 12 10 12 10 13 12  9  5  6  8  8 
10 10 11  8  9  7  5
  [91]  4  6  7  6  9  7  6  4  5  3

Roger could confirm that it is correct !



At 10:05 16/12/2004, Marius Gilbert wrote:
>Dear colleagues,
>
>I have a 500 by 500 matrix with presence or absence value in each cell as
>an input matrix. I am trying to create an output matrix having in each
>cell the sum of the values from neigbouring cells in the input matrix
>according to a moving-window defined as:
>
>0 1 1 1 0
>1 1 1 1 1
>1 1 0 1 1
>1 1 1 1 1
>0 1 1 1 0
>
>where the output cell receiving the values is located in the center. I
>have written a function that loop over the cells of the output matrix, and
>sum up the values from these neigbouring cells. It works, but it is fairly
>slow, and hangs if I try it over a larger matrix. Given that this is a
>rather basic function available in most raster GIS packages (IDRISI and AV
>Spatial Analyst) and running fairly quickly, I wondered whether anyone had
>previously come accross a similar function in an existing R-package.
>
>Any helps  or pointer would be appreciated,
>
>Many thanks in advance,
>
>Marius
>
>_______________________________________________
>R-sig-Geo mailing list
>R-sig-Geo at stat.math.ethz.ch
>https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Stéphane DRAY
-------------------------------------------------------------------------------------------------- 

Département des Sciences Biologiques
Université de Montréal, C.P. 6128, succursale centre-ville
Montréal, Québec H3C 3J7, Canada

Tel : (514) 343-6111 poste 1233         Fax : (514) 343-2293
E-mail : stephane.dray at umontreal.ca
-------------------------------------------------------------------------------------------------- 

Web                                          http://www.steph280.freesurf.fr/




More information about the R-sig-Geo mailing list