title: Function to sum each grid cells of raster stack using other rasters as an indicator
body: <pre><code>## input raster
  s &lt;- stack(list.files("~/dailyraster", full.names=TRUE)) # daily raster stack
  r_start &lt;- raster("~/stackSumSTART.asc") # this raster contain starting Julian day
  r_end &lt;- raster("~/stackSumEND.asc") # this raster contain ending Julian day
  noNAcells &lt;- which(!is.na(r[])) # cell numbers which contain values
  
  ## dummy raster
  x &lt;- r
  x[] &lt;- NA 
  
  ## loop
  for (i in noNAcells) {      
    x[i] &lt;- sum(s[[r_start[i]:r_end[i]]][i])
  }
  </code></pre>
  
  <p>I would like to create a function like <code>stackApply()</code>, but I want it to work on a cell basis.</p>
  
  <p>Above is a <code>for()</code> loop version and it works well, but it takes too much time.</p>
  
  <p>The point is that each cell gets the range of <code>sum()</code> from two raster layers, <code>r_start</code>, <code>r_end</code> in above script.</p>
  
  <p>Now I am struggling to transform this code using <code>apply()</code> family.</p>
  
  <p>Is there any possibility to improve the speed with <code>for()</code> loop? or please give me some tips to write this code in <code>apply()</code></p>
  
  <p>Any comments will help me, thank you.</p>