Skip to content
Prev 248853 / 398506 Next

How to do a moving window on standard deviation

I'd like to use vectorization to take a 4 point moving window on standard
deviation on the close column and create another variable (st.dev) in the
dataframe. Here's the dataframe


head(xyz)
        Date Close
1 2011-01-28 56.42
2 2011-01-27 57.37
3 2011-01-26 56.48
4 2011-01-25 56.39
5 2011-01-24 55.74
6 2011-01-21 55.46

So the first 3 elements to the new st.dev column would be zero (c(rep(0,3)),
then the 4th element of the new std.dev column would be standard deviation
of the first 4 closes. Next element would be sd of Close[5]:Close[1], then
sd of Close[6]: Close[2] ...and so on until the last row of xyz.

There must be an easy vetorized way to do this but I don't see it. Sorry for
the basic question but continuing to figure this new language out.

Thanks in advance for the help