以下可能是有用的:
xx = structure(c(0.0379, -8e-04, 0.0352, 0.0379, 0.0392, 0.0173, 0.036,
0.0371), .Names = c("2014-02-05", "2014-02-06", "2014-02-07",
"2014-02-12", "2014-02-14", "2014-02-17", "2014-02-18", "2014-02-19"
))
xx
2014-02-05 2014-02-06 2014-02-07 2014-02-12 2014-02-14 2014-02-17 2014-02-18 2014-02-19
0.0379 -0.0008 0.0352 0.0379 0.0392 0.0173 0.0360 0.0371
yy = as.numeric()
for(i in 5:length(xx)){
yy[i]= sd(xx[(i-4):i])
}
yy
[1] NA NA NA NA 0.017212408 0.017278108 0.008982038 0.009130991
對於數據幀版本:
ddf = structure(list(date = structure(1:8, .Label = c("2014-02-05",
"2014-02-06", "2014-02-07", "2014-02-12", "2014-02-14", "2014-02-17",
"2014-02-18", "2014-02-19"), class = "factor"), value = c(0.0379,
-8e-04, 0.0352, 0.0379, 0.0392, 0.0173, 0.036, 0.0371)), .Names = c("date",
"value"), class = "data.frame", row.names = c(NA, -8L))
ddf
date value
1 2014-02-05 0.0379
2 2014-02-06 -0.0008
3 2014-02-07 0.0352
4 2014-02-12 0.0379
5 2014-02-14 0.0392
6 2014-02-17 0.0173
7 2014-02-18 0.0360
8 2014-02-19 0.0371
ddf$rolling_sd=0
for(i in 5:nrow(ddf)){
ddf$rolling_sd[i]= sd(ddf$value[(i-4):i])
}
ddf
date value rolling_sd
1 2014-02-05 0.0379 0.000000000
2 2014-02-06 -0.0008 0.000000000
3 2014-02-07 0.0352 0.000000000
4 2014-02-12 0.0379 0.000000000
5 2014-02-14 0.0392 0.017212408
6 2014-02-17 0.0173 0.017278108
7 2014-02-18 0.0360 0.008982038
8 2014-02-19 0.0371 0.009130991
非常不清楚這個問題,它是...你能提供一些例子所需的輸出爲上面的設置? – 2014-08-31 11:25:35
@ user3785531:我們將非常感謝您對答案的反饋意見。 – rnso 2014-09-01 00:56:23