title: Moving standard deviation in R
body: <p>I want to compute any type of "moving statistic" on a time series in R, beyond a moving average. For example, how would I compute a moving standard deviation over a time window of length 3?</p>
  
  <p>I've tried the following:</p>
  
  <pre><code>#example data
  x &lt;- c(3,9,2,8,4,6,5,8)
  #moving standard deviation over a time window of length 3
  msd3 &lt;- (cumsum(x^2)-cumsum(Lag(x^2,3)))/((1:length(x))-(Lag(1:length(x),3)))-((cumsum(x)-cumsum(Lag(x,3)))/((1:length(x))-(Lag(1:length(x),3))))^2
  </code></pre>
  
  <p>But not only does it not work (because the cumsum of the lagged vector gives a vector of all NAs), but I stopped trying to solve that last issue because it seems unnecessarily complicated. Any elegant solution to that problem?</p>