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; data Revenue; array Goal _temporary_; *Load the temporary array with values; if _n_ = 1 then do Year = 1 to 10; input Goal[Year] @; end; *Now input the sales data; input Name $ Year Sales; Difference = Sales – Goal[Year]; datalines; 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; run;
Here is the output:
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.
You can learn more about temporary arrays from my book, Learning SAS by Example: A Programmer's Guide, available from SAS Press.