I am currently trying to develop a new function that calculates rolling statistics by groups within a matrix.
My dataset looks as follows:
ID year ROA CAR
[1,] 1 2009 0.006954926 0.3933436
[2,] 1 2010 0.013286958 0.2892719
[3,] 1 2011 0.012334294 0.2402294
[4,] 1 2012 0.006843720 0.2088247
[5,] 1 2013 0.004888144 0.1757100
[6,] 2 2006 0.010172563 0.0511171
As is noticeable, the data is grouped by ID, which contains yearly observations for ROA and CAR. If you are interested, the data comes from banks, and represents the Return on Assets, and the Capital to Asset Ratio.
My goal is to create a function that estimates a standardised z-score specified as follows:
z = (mean(ROA) + mean(CAR)) / sd(ROA)
However, the score is based on rolling measures of the mean and the standard deviation for a window length of 3, which needs to be computed by an ID basis as the data is indexed by ID and year.
I am trying to specify my code and I have come up with something like this:
z <- rollapply(data, 3, function(x) x(((rollapply(data[,3], 3, mean))
- (rollapply(data[,4], 3, mean))) / (rollapply(data[,3], 3,
sd)))
As is noticeable, I am using the rollapply function to compute the rolling means and the rolling standard deviations, however, I am not sure how to do this for an ID basis. It would be extremely helpful to know how I may do so....