title: Implementing which.max() on an R RasterStack for each cell
body: <p>UPDATE 09/17/2012</p>
  <p>Here is a piece of code using self-contained data that reproduces my issues:</p>
  <p>Please keep in mind, the actual data dimensions I have are huge...</p>
  <p>dimensions  : 3105, 7025, 21812625, 12  (nrow, ncol, ncell, nlayers)</p>
  <p>What I need is the index of the max for each row,col over the layers. All NA should return NA and multiple max copys should return the first max index (or something else, must be consistent)</p>
  <pre><code># Create a test RasterStack
  
  require(raster)
  
  a &lt;- raster(matrix(c(11,11,11,
                       NA,11,11,
                       11,11,13),nrow=3))
  
  b &lt;- raster(matrix(c(12,12,12,
                       NA,12,12,
                       40,12,13),nrow=3))
  
  c &lt;- raster(matrix(c(13,9,13,
                       NA,13,13,
                       13,NA,13),nrow=3))
  
  d &lt;- raster(matrix(c(10,10,10,
                       NA,10,10,
                       10,10,10),nrow=3))
  
  corr_max &lt;- raster(matrix(c(13,12,13,
                              NA,13,13,
                              40,12,13),nrow=3))
  
  stack &lt;- stack(a,b,c,d)
  
  
  which.max2 &lt;- function(x, ...)which.max(x)
  
  # stackApply method
  max_v_sApp &lt;- stackApply(stack,rep(1,4),which.max2,na.rm=NULL)
  
  # calc method
  max_v_calc &lt;- calc(stack,which.max)
  </code></pre>
  <p>Hopefully this provides enough information.</p>
  <p>UPDATE:</p>
  <p>This might work... testing now:</p>
  <pre><code>which.max2 &lt;- function(x, ...){
    max_idx &lt;- which.max(x)   # Get the max
    ifelse(length(max_idx)==0,return(NA),return(max_idx))
  }
  </code></pre>