SUPPORT / SAMPLES & SAS NOTES
 

Support

Sample 41380: Calculate rolling sums and averages using arrays

DetailsCodeOutputAboutRate It

The sample code on the Full Code tab illustrates how to calculate rolling sums and rolling averages by defining an array to hold the values for the most recent number of desired periods. Once the array contains the desired values, the calculation of the sum, using the SUM function, and the average, using the MEAN function, is straight-forward. You can simply pass the array to either function to obtain the desired statistic:

  _sum_ = sum(of array_name[*]);  
  _avg_ = mean(of array_name[*]);  

This sample emphasizes the logic needed to always have the most recent periods in the array before calculating the next set of rolling statistics. The concept of removing the oldest value and replacing it with the most recent value is commonly referred to as FIFO - First In, First Out.

Once the array has been populated with the initial number of periods, the rolling statistics are calculated. A counter variable is used to keep track of and specify the element in the array containing the oldest value and to which the new most recent value should be assigned. The new value over-writes the oldest value. After an assignment is performed, new rolling statistics are calculated. This process continues until the last value contributing to the statistics has been read from the data source.

Note: Other rolling statistics could also be calculated, such as the standard deviation:

  _std_ = std(of array_name[*]);  



These sample files and code examples are provided by SAS Institute Inc. "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. Recipients acknowledge and agree that SAS Institute shall not be liable for any damages whatsoever arising out of their use of this material. In addition, SAS Institute will provide no support for the materials contained herein.