I have a dataframe which has 7 variables which I would like to apply a rolling normalising window to. My dataframe has no NA values and all variables are of the same length.
> head(CK0159U09A3,10)
W1 W2 W3 W4 W5 W6 W7
1 1.37853716 0.01316304 -0.1363012 0.6895341 -0.7230930 -0.1310321 -0.4109521
2 -0.73032998 0.31212925 0.1654731 0.9187255 -0.8017260 -0.1619631 -0.4243575
3 -0.52130420 0.43831484 0.6088623 1.1183964 -0.8486971 -0.1970389 -0.4368820
4 0.55501096 0.13850401 1.1221211 1.2708212 -0.8701385 -0.2372061 -0.4490060
5 -0.06995122 -0.53842548 1.4592013 1.3581935 -0.8661200 -0.2791726 -0.4608654
6 -0.19984548 -0.78829431 1.4564180 1.3823090 -0.8431200 -0.3184653 -0.4722506
7 0.68935525 0.18733222 1.0158497 1.3344059 -0.8043461 -0.3526886 -0.4825229
8 -0.49540738 0.80663376 0.1774945 1.1800970 -0.7494087 -0.3803636 -0.4901212
9 -0.09501622 -0.17931684 -0.7074083 0.9312984 -0.6801124 -0.4008524 -0.4942994
10 -0.14939548 -0.68153738 -1.2723772 0.6054420 -0.5968207 -0.4149125 -0.4952316
My window is defined as size 3
windowSize <- 3
I would like to apply a rolling window of size = 3 to each variable within my dataframe. The normalising function uses the following logic:
- calculates the standard deviation of the entire variable (length(CK0159U09A3[,1].....)
- then applies the window of size = 3 to the first 3 values and calculates their averages
- For the first value in the window it subtracts the average of the three values and then divides by the standard deviation
- The function then increments by 1 and performs the same steps on the next three values for all 7 columns.
I know about the rollapply/r functions in zoo but I can't fathom how to write the section about taking the current value and performing the subtraction and division and then incrementing to the next value. If you can't tell already, I am not a strong programmer.
I believe it's already been captured in the first answer below but when the sliding window reaches the end of the column and there are less values than the window size then NAs should be returned.
Any help in cracking this would be greatly appreciated.
Just for clarity here is the logic I am trying to implement with math
1.3785 - ((1.378+(-0.7303)+(-0.5213)/windowSize))/S.D of column
-0.7303 - ((-0.7303+(-0.5213)+0.555)/windowSize))/S.D of column
-0.5213 - ((-0.5213+0.555+(-0.0699))/windowSize))/S.D of column