Now that you have grouped
the variables and you know how many times the loop is processed, you
must tell SAS which variable in the array to use in each iteration
of the loop. Recall that variables in an array can be identified by
their array references, and that the subscript of the reference can
be a variable name as well as a number. Therefore, you can write programming
statements in which the index variable of the DO loop is the subscript
of the array reference:
array-name {index-variable}
When the value of the
index variable changes, the subscript of the array reference (and,
therefore, the variable that is referenced) also changes.
The following statement
uses the index variable Count as the subscript of array references:
if changelist{Count} = . then changelist{Count} = 0;
You can place this statement
inside an iterative DO loop. When the value of Count is 1, SAS reads
the array reference as CHANGELIST{1} and processes the IF-THEN statement
on CHANGELIST{1}, that is, Museums. When Count has the value 2 or
3, SAS processes the statement on CHANGELIST{2}, Galleries, or CHANGELIST{3},
Other. The complete iterative DO loop with array references looks
like this:
do Count = 1 to 3;
if changelist{Count} = . then changelist{Count} = 0;
end;
These statements tell
SAS to do the following processing:
-
perform the actions in the loop
three times
-
replace the array subscript Count
with the current value of Count for each iteration of the IF-THEN
statement
-
locate the variable with that array
reference and process the IF-THEN statement on that variable
The following DATA step
uses the ARRAY statement and iterative DO loop:
libname mylib 'permanent-data-library';
data changes;
set mylib.attractions;
array changelist{3} Museums Galleries Other;
do Count = 1 to 3;
if changelist{Count} = . then changelist{Count} = 0;
end;
run;
proc print data=changes;
title 'Tour Attractions';
run;
The following output
displays the results.
Display 14.3 Using an Array and an Iterative DO Loop to Produce a Data Set
The data set CHANGES
shows that the missing values for the variables Museums, Galleries,
and Other are now zero. In addition, the data set contains the variable
Count with the value 4 (the value that caused processing of the loop
to cease in each observation).
To exclude Count from
the data set, use a DROP= data set option:
data changes2 (drop=Count)
;
set mylib.attractions;
array changelist{3} Museums Galleries Other;
do Count = 1 to 3;
if changelist{Count} = . then changelist{count} = 0;
end;
run;
proc print data=changes2;
title 'Tour Attractions';
run;
The following output
displays the results.
Display 14.4 Dropping the Index Variable from a Data Set