Arrays
Prerequisites: DO loops
A SAS array is a temporary name for a group of variables, so you can process them in a loop instead of writing the same statement ten times. It isn't stored in the data set — the variables are.
Cleaning many columns at once
A survey uses 9 for "no answer" in questions q1–q5:
data survey;
input id q1-q5;
array q{5} q1-q5;
do i = 1 to 5;
if q{i} = 9 then q{i} = .;
end;
answered = n(of q1-q5);
avg = mean(of q{*});
format avg 4.2;
drop i;
datalines;
1 4 5 9 3 4
2 2 9 9 1 5
;
run;
proc print data=survey noobs;
run;
id q1 q2 q3 q4 q5 answered avg
1 4 5 . 3 4 4 4.00
2 2 . . 1 5 3 2.67
q1-q5is a variable list:q1 q2 q3 q4 q5.array q{5} q1-q5;—q{1}isq1,q{2}isq2, and so on. Braces, brackets, or parentheses all work.of q{*}orof q1-q5passes every element to a function.N()counts non-missing values;MEAN()ignores missing values.dim(q)returns the number of elements — usedo i = 1 to dim(q);so the loop stays right if the array changes.
Wide to long
Arrays with OUTPUT turn one row per person into one row per value:
data long;
set survey;
array q{5} q1-q5;
do question = 1 to 5;
answer = q{question};
output;
end;
keep id question answer;
run;
proc print data=long(obs=6) noobs;
run;
id question answer
1 1 4
1 2 5
1 3 .
1 4 3
1 5 4
2 1 2
PROC TRANSPOSE does the same job; arrays give you more control.
Temporary arrays
_TEMPORARY_ arrays hold values without creating variables — ideal for
lookup tables:
data _null_;
array limits{3} _temporary_ (50 70 90);
score = 75;
level = 0;
do i = 1 to dim(limits);
if score >= limits{i} then level = i;
end;
put score= level=;
run;
score=75 level=2
Character arrays
Add $ and a length for character variables:
array names{3} $ 20 name1-name3;. array nums{*} _numeric_; and
array chars{*} _character_; cover every numeric or character variable
in the step.
Common mistakes
ERROR: Array subscript out of range— the loop goes past the last element; usedim().- Mixing types — every element must be numeric or every element must be character.