Zane Wubbena, PhD > Writing
SAS Array Counting Guide
How to use arrays and loops in SAS to count conditional values.
Overview
Schools are assigned annual special education determination levels (DL):
- DL 1: Meets Requirements
- DL 2: Needs Assistance
- DL 3: Needs Intervention
- DL 4: Needs Substantial Intervention
The problem: count how many variables in a SAS dataset hold a specific determination level value, in this case 4. That count supports data summarization, tracking how often a condition occurs, and reporting under OSEP QA 23-01.
The solution uses two SAS programming elements: an array to group related variables, and a do loop to check each variable in turn. The loop examines each variable in the array, counts occurrences of the value 4, and stores the final count in a new variable, TOTAL_NSI_CNT.
Steps
-
1
Initialize the counter
Before the loop starts, set a starting value for the variable that will hold the count. TOTAL_NSI_CNT starts at 0 because nothing has been counted yet, so the counter starts fresh for each row of data.
TOTAL_NSI_CNT = 0;
-
2
Define the array
An array groups several variables so the same logic applies to all of them without repeating code. Here the array dv_vars holds seven variables, DL_18 through DL_24.
array dv_vars[7] DL_18 DL_19 DL_20 DL_21 DL_22 DL_23 DL_24;
-
3
Start the do loop
A do loop repeats a set of instructions a set number of times. Here it visits each variable in the array. The counter i tracks which element is being processed, and dim(dv_vars) returns the number of elements, 7 in this case, so the loop runs from 1 to 7.
do i = 1 to dim(dv_vars);
-
4
Check the condition
Inside the loop, the code checks whether the current element equals 4. If it does, the counter goes up by 1. If the counter ends at 3, three of the seven variables held a value of 4.
if dv_vars[i] = 4 then TOTAL_NSI_CNT + 1;
-
5
Drop the loop index
Once the loop finishes, the index variable i is no longer needed, so it is dropped from the dataset.
drop i;
Full program
TOTAL_NSI_CNT = 0; array dv_vars[7] DL_18 DL_19 DL_20 DL_21 DL_22 DL_23 DL_24; do i = 1 to dim(dv_vars); if dv_vars[i] = 4 then TOTAL_NSI_CNT + 1; end; drop i;
Key concepts
- Initialize a variable. Set a starting value before using it (TOTAL_NSI_CNT = 0).
- Array. A collection of variables treated as a group (dv_vars).
- Do loop. Repeats a set of instructions a specified number of times.
- i. The loop counter; tracks the current position in the array.
- dim(). Returns the number of elements in the array.
- Element. Each individual variable inside an array.
- Incrementing the counter. Adding 1 to a counter each time a condition is met.
- Drop. Removes variables that are no longer needed, such as i, from the final dataset.
The array groups the variables so one rule applies to all of them, and the loop checks each one and updates the counter. The same pattern works anywhere a count has to be summarized across many variables.