In statistics, a moving average represents the average of the previous n values in a dataset.
The easiest way to calculate a moving average in SAS is to use the proc expand statement.
The following example shows how to use this statement in practice.
Example: Calculate a Moving Average in SAS
Suppose we create the following dataset in SAS:
/*create dataset*/ data original_data; input time values; datalines; 1 7 2 12 3 14 4 12 5 16 6 18 7 11 8 10 9 14 10 17 ; run; /*view dataset*/ proc print data=original_data;
Now suppose we would like to calculate a 3-period moving average for the values column.
We can use proc expand to do so:
/*calculate 3-period moving average for values*/
proc expand data=original_data out=out_data method=none;
id time;
convert values = values_ma3 / transout=(movave 3);
run;
/*view results*/
proc print data=out_data;
The new column called values_ma3 displays the 3-period moving average for the values column.
For example, the third value in the values_ma3 column represents the average of the previous 3 periods:
- Moving Average = (7+12+14) / 3 = 11.0000
The fourth value in the values_ma3 column represents the average of the previous 3 periods as well:
- Moving Average = (12+14+12) / 3 = 12.6667
And so on.
To calculate the moving average for a different number of periods, simply change the value after movave in the code.
For example, we could use the following code to calculate a 4-period moving average for the values column:
/*calculate 4-period moving average for values*/
proc expand data=original_data out=out_data method=none;
id time;
convert values = values_ma4 / transout=(movave 4);
run;
/*view results*/
proc print data=out_data;
The new column called values_ma4 displays the 4-period moving average for the values column.
Additional Resources
The following articles explain how to perform other common tasks in SAS:
How to Identify Outliers in SAS
How to Calculate Percentiles in SAS
How to Calculate Mean, Median, & Mode in SAS