title: R: Calculating Pearson correlation coefficient in each cell along time line
body: <p>I have two sets of rasters, both with same x,y,z extent. I've made two stacks: stacka and stackb. I want to calculate the Pearson correlation coefficient (<a href="http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient" rel="nofollow">PCC</a>) in each grid cell between two stacks along the time line. I've made a simpler example (forgive me with the dumb way of creating rasters)</p>
  
  <pre><code>a1&lt;-c(1,1,1,1,1,1,1,1,NA)
  a2&lt;-c(2,2,2,2,1,2,2,NA,2)
  a3&lt;-c(3,3,3,3,3,2,NA,3,3)
  b1&lt;-c(2,2,2,2,2,2,2,2,2)
  b2&lt;-c(3,3,3,3,3,3,3,3,3)
  b3&lt;-c(4,4,4,4,4,4,4,4,4)
  matrixa1&lt;-matrix(a1,3,3)
  matrixa2&lt;-matrix(a2,3,3)
  matrixa3&lt;-matrix(a3,3,3)
  matrixb1&lt;-matrix(b1,3,3)
  matrixb2&lt;-matrix(b2,3,3)
  matrixb3&lt;-matrix(b3,3,3)
  rastera1&lt;-raster(matrixa1)
  rastera2&lt;-raster(matrixa2)
  rastera3&lt;-raster(matrixa3)
  rasterb1&lt;-raster(matrixb1)
  rasterb2&lt;-raster(matrixb2)
  rasterb3&lt;-raster(matrixb3)
  stacka&lt;-stack(rastera1,rastera2,rastera3)
  stackb&lt;-stack(rasterb1,rasterb2,rasterb3)
  
  a_bar&lt;-calc(stacka,mean,na.rm=TRUE)
  b_bar&lt;-calc(stackb,mean,na.rm=TRUE)
  numerator&lt;-setValues(rastera1,0)
  denominator1&lt;-numerator
  denominator2&lt;-numerator
  for(i in 1:noflayers){
    numerator&lt;-numerator+(stacka[[i]]-a_bar)*(stackb[[i]]-b_bar)
    denominator1&lt;-denominator1+(stacka[[i]]-a_bar)^2
    denominator2&lt;-denominator2+(stackb[[i]]-b_bar)^2
  }
  pearsoncoeff&lt;-numerator/sqrt(denominator1*denominator2)
  </code></pre>
  
  <p>In the end I have a raster with each grid cell filled with PCC. The problem is, data a is intermittent, some grids are NA in some layers. So the end product has some blanks. My algorithm spits out "NA" when it encounters NA. I'd need some option like <code>na.rm=TRUE</code> in the calculation, so the output would calculate whatever months have values.</p>
  
  <p>The method I can think of is to use <code>is.na(stacka[[nlayers]][nrows,ncols]==FALSE</code> and find corresponding pair in stackb, but that's on cell basis,which'd take enormous amount of computer time.</p>