SAS temporary arrays are an underutilized jewel in the SAS toolbox. I find that many beginning to intermediate SAS programmers are not familiar with temporary arrays. The good news is that there is nothing complicated about them and they are very useful. First of all, what is a temporary array?
Let’s start with a “regular” array like this:
array x x1-x10;
This array, called x is associated with the 10 variables x1-x10. (Remember, the array name can be any valid SAS name, it doesn’t have to have any relationship to the variables—but it usually does.) Now, how about a temporary array?
array y _temporary_;
You use the keyword _TEMPORARY_ where you usually enter your variable names. There are no variables associated with a temporary array. In this example, you could reference y or y, etc. but there are no variables y1, y2, etc.
My favorite use of a temporary array is for table lookup. You can load the elements of a temporary array and then use those elements to hold values. Here is an example:
You have sales goals for years 1-10 and the sales figures for all of your salespeople for these 10 years. You want to compare each person’s sales with the goals for the 10 years. By placing the 10 sales goals in a temporary array, you can retrieve the goal amount by knowing the year. The temporary array elements are automatically retained and stored in memory, so they are a perfect for tasks such as this. Take a look at the following program to see how this works:
*Program to demonstrate temporary arrays;
array Goal _temporary_;
*Load the temporary array with values;
if _n_ = 1 then do Year = 1 to 10;
input Goal[Year] @;
*Now input the sales data;
input Name $ Year Sales;
Difference = Sales – Goal[Year];
10 11 14 15 18 20 23 28 30 33
Fred 3 16
Joan 1 11
Helen 8 45
title “Listing of Data Set Revenue”;
proc print data=Revenue noobs;
Here is the output:
You might want to define an array such as Goal like this:
array Goal[2001:2010] _temporary_;
where the subscript can be the actual value for a year. Notice the colon between the two years. This causes the subscripts for this array range from 2001 to 2010. Also, because arrays can be multi-dimensional, you can perform multi-way lookups. Give it a try.