Arrays from A to Z
16. May 2007 01:19Arrays from A to Z
by Phil Spector
Arrays are a convenient way of grouping variables,and can be used for simple repetitive tasks, reshaping data sets, and \remembering" values from observation-to-observation. Arrays can be used to allow some traditional matrix-style programming techniques to be used in the data step.
Array Statement: Syntax:
ARRAY name<fnelemg> <$> <<elements <(initial-values)>>;
Examples:
array x x1-x3;
array check{5} _temporary_;
array miss{4} _temporary_ (9 9 99 9);
array dept $ dept1-dept4 ('Sales','Research','Training');
array value{3}; * generates value1, value2 and value3;
- All variables in an array must have the same type (numeric or character).
- An array name can't have the same name as a variable .
- You must explicitly state the number of elements when using
_temporary_; in other cases SAS figures it out from context,generating new variables if necessary.
Advanced Features of Arrays :
Using Parallel Arrays:
data new;
set old;
array x x1-x10;
array mval _temporary_ (9 9 9 9 9 99 99 99 99 99);
do i=1 to dim(x);
if x{i} = mval{i} then x{i} = .;
end;
run;Another Example of the array Statement :
array class class1-class5;
total = 0;
do i = 1 to 5 until(total >= 10);
total = total + class{i};
end;
year = i;
if total lt 10 then year = .;Reshaping Data Sets: I. One to Many:
Consider a data set with 4 variables (x1-x4) stored as follows: ID X1 X2 X3 X4 1 17 19 22 24 2 18 14 33 16 3 19 28 31 42The goal is to create four observations for each original observation, one for each variable.
data new;
set old;
array xx x1-x4;
do time=1 to 4;
x = xx{time};
output;
end;
drop x1-x4;Reshaping Data Sets: Example 2:
Consider the transformed data set from the previous example. Suppose we wish to put it back to it's original form:
data next;
set new;
by id;
array xx x1-x4;
retain xx;
if first.id then do i=1 to 4;xx{i} = .;end;
xx{time} = x;
if last.id then output;
drop x i;
run;
Email 