[R] How to do a moving window on standard deviation

Pete Brecknock Peter.Brecknock at bp.com
Sun Jan 30 21:03:55 CET 2011


One way is to convert your data into a zoo object and use the rollapply
function

# Your data
lines = "Date Close
2011-01-28 56.42
2011-01-27 57.37
2011-01-26 56.48
2011-01-25 56.39
2011-01-24 55.74
2011-01-21 55.46"

d = read.table(textConnection(lines), header = TRUE) 

# create zoo object
d.z=zoo(d[,-1],order.by=as.Date(d$Date))

# generate rolling std devs
sd.z = rollapply(d.z,5,sd,align="right")

# you wanted a data frame 
df = as.data.frame(merge(d.z,sd.z,all=TRUE))

HTH

Pete
-- 
View this message in context: http://r.789695.n4.nabble.com/How-to-do-a-moving-window-on-standard-deviation-tp3247566p3247592.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list