title: calculate average correlation for neighboring pixels through time
body: <p>I have a stack of 4 rasters.  I would like the average correlation through time between a pixel and each of its 8 neighbors.</p>
  
  <p>some data:</p>
  
  <pre><code>library(raster)  
  
  r1=raster(matrix(runif(25),nrow=5))
  r2=raster(matrix(runif(25),nrow=5))
  r3=raster(matrix(runif(25),nrow=5))
  r4=raster(matrix(runif(25),nrow=5))
  s=stack(r1,r2,r3,r4)
  </code></pre>
  
  <p>so for a pixel at position x, which has 8 neighbors at the NE, E, SE, S etc positions, I want the average of</p>
  
  <pre><code>cor(x,NE)
  cor(x,E)
  cor(x,SE)
  cor(x,S)
  cor(x,SW)
  cor(x,W)
  cor(x,NW)
  cor(x,N)
  </code></pre>
  
  <p>and the average value saved at position x in the resulting raster. The edge cells would be NA or, if possible a flag to calculate the average correlation just with the cells it touches (either 3 or 5 cells).
  Thanks!</p>