title: Efficient calculation of matrix cumulative standard deviation in r
body: <p>I recently posted this question on the r-help mailing list but got no answers, so I thought I would post it here as well and see if there were any suggestions.</p>
  
  <p>I am trying to calculate the cumulative standard deviation of a matrix. I want a function that accepts a matrix and returns a matrix of the same size where output cell (i,j) is set to the standard deviation of input column j between rows 1 and i. NAs should be ignored, unless cell (i,j) of the input matrix itself is NA, in which case cell (i,j) of the output matrix should also be NA.</p>
  
  <p>I could not find a built-in function, so I implemented the following code. Unfortunately, this uses a loop that ends up being somewhat slow for large matrices. Is there a faster built-in function or can someone suggest a better approach?</p>
  
  <pre><code>cumsd &lt;- function(mat)
  {
      retval &lt;- mat*NA
      for (i in 2:nrow(mat)) retval[i,] &lt;- sd(mat[1:i,], na.rm=T)
      retval[is.na(mat)] &lt;- NA
      retval
  }
  </code></pre>
  
  <p>Thanks.</p>