Skip to main content
v2026.11,986 entries · CC-BY 4.0

SAS Array: Syntax, DO Loops and Worked Example

Use SAS arrays to process repeated measurements with paired input and output columns, a DIM-based loop and a hand-checkable example.

Written and maintained by CASRAI Editorial Board

Published

On this page

A SAS array groups variables so a DATA step can apply the same operation to each through an index. The ARRAY statement defines that grouping; a DO loop processes its elements. Use arrays for repeated measurements, parallel derived columns and other tasks that would otherwise repeat similar assignment statements.

What SAS arrays are used for in research

For a researcher preparing repeated measurements, the useful feature is the connection between one rule and several named columns. Suppose a data set holds three visits in separate variables. An array lets you write the transformation once and apply it to each visit, while keeping the visit variables available individually afterward. SAS’s training lesson illustrates this pattern with conversions and differences between successive measurements.

Start with the distinction between the array name and its elements. In array visits{3} visit1 visit2 visit3;, visits is the reference name; visit1, visit2 and visit3 are the variables. The declaration does not create a separate stored column called visits. SAS describes the grouping as local to the DATA step. A later step needs its own declaration if it wants to use that array name.

The example below uses separate raw and cleaned columns. That is an editorial choice to make each change inspectable: the reader can compare the input value with the output value at the same visit. For the surrounding language structure, see DATA steps and a first SAS program.

Install or access SAS

ARRAY is part of DATA step programming; there is no separate array package to install. You need a SAS programming session that can execute the statements shown here. The example uses in-stream data and an ordinary SAS DATA step, rather than a DATA step running in CAS: the SAS reference specifically excludes DATALINES and list INPUT from CAS execution.

For learning, SAS offers OnDemand for Academics through SAS Studio in a browser. Its official page describes access for students, educators and independent learners without local software installation or management. Follow the official SAS OnDemand for Academics access page. Its learning scope should not be read as authorization to upload a project’s confidential research records.

Use the synthetic records below to understand the program before adapting it to an approved research environment. The task requires no external file, library path or imported participant data.

Step-by-step task: create an array in SAS

Illustrative composite: these three records are invented for teaching. Assume this example’s data dictionary defines 999 as a missing-value code for each visit. That definition belongs to this example only; it is not a SAS rule or a recommendation for coding real measurements.

  1. Read the input columns. INPUT names an identifier and three raw visit values. DATALINES supplies the small test fixture directly in the program.
  2. Declare the source array. The explicit list connects the three positions to raw_visit1, raw_visit2 and raw_visit3. The identifier stays outside that list.
  3. Declare matching output columns. The second array groups clean_visit1 through clean_visit3. Position 1 in each array represents the same visit; keep that alignment when adapting the example.
  4. Reset the change counter. Assign zero before the loop for each input record. It counts replacements in that record, rather than accumulating across the whole input.
  5. Loop over the visits. Copy the raw value first. If it equals the example’s missing code, replace the cleaned value with a numeric missing value and increment the counter.
  6. Inspect the result. DROP excludes the working index from output. PROC PRINT displays the raw values, cleaned values and replacement count together.
data array_demo;
  input id raw_visit1 raw_visit2 raw_visit3;
  array raw_visit{3} raw_visit1 raw_visit2 raw_visit3;
  array clean_visit{3} clean_visit1 clean_visit2 clean_visit3;

  n_replaced = 0;
  do i = 1 to dim(raw_visit);
    clean_visit{i} = raw_visit{i};
    if raw_visit{i} = 999 then do;
      clean_visit{i} = .;
      n_replaced = n_replaced + 1;
    end;
  end;
  drop i;
  datalines;
101 12 999 18
102 999 999 20
103 14 16 .
;
run;

proc print data=array_demo noobs;
  var id raw_visit1 raw_visit2 raw_visit3
         clean_visit1 clean_visit2 clean_visit3 n_replaced;
run;

Read the array reference inside the loop

On the first pass, i is 1, so the assignment copies raw_visit1 into clean_visit1. On the next pass it copies the second pair, then the third. The condition changes only the corresponding cleaned value. The raw variables remain available for comparison because the code never assigns a new value to them.

DIM supplies the element count. With the default lower bound of 1, do i = 1 to dim(raw_visit); traverses the complete array. If you later add a visit, update both declarations and their aligned variable lists. DIM avoids a separate hard-coded loop endpoint, but it cannot determine whether you paired the correct research variables.

The DATA step also illustrates why assignment placement matters. Moving n_replaced = 0; inside the loop would erase earlier replacements within the same record. Removing the assignment and changing the counter’s retention behavior would be a different program. Keep the per-record objective visible in the code.

Output and how to read it

The expected cleaned values and counts below are derived from the displayed synthetic inputs and transformation rule. They are a hand-checkable expectation, not a reported SAS execution result.

ID Cleaned visit 1 Cleaned visit 2 Cleaned visit 3 Replacements
101 12 . 18 1
102 . . 20 2
103 14 16 . 0

For ID 101, the only equality with 999 occurs at visit 2. For ID 102, visits 1 and 2 both match, giving two replacements. ID 103 already has a missing third visit; it does not match 999, so the counter stays zero. Across the fixture there are three replacements, although the cleaned visit columns contain four missing entries. This difference is intentional: the counter measures recoding, not all missingness.

Check both sides of each pair. A changed identifier, an overwritten raw value or a cleaned value in the wrong visit position would contradict this task even if the total replacement count looked plausible. The distinct values 12, 18, 20, 14 and 16 help reveal a positional error that three identical values could hide.

When adapting the fixture, add a record with no missing-code values and another with the code at every visit. These are suggested checks for this particular rule: their expected replacement counts are zero and three. Keep the existing record with an already-missing value as well, because it distinguishes copying missingness from performing a replacement.

To inspect variable types and other data-set attributes separately, use PROC CONTENTS in SAS. The declaration dataset below this article compares other array forms; it serves a different purpose from the expected-output table above.

Troubleshooting arrays in SAS

Confusing the number of elements with the upper bound

DIM reports a count; HBOUND reports the endpoint. For an array indexed from 0 through 2, there are three elements, but 2 is the largest valid subscript. A loop from 1 through DIM would skip position 0 and attempt position 3. SAS documents LBOUND and HBOUND for loops that follow the declared bounds.

data bounds_demo;
  array slot{0:2} slot0 slot1 slot2;
  do i = lbound(slot) to hbound(slot);
    slot{i} = i;
  end;
  drop i;
run;

In this separate illustrative example, the assignments should produce slot0=0, slot1=1 and slot2=2. That expected mapping follows the actual subscript values, rather than the order of passes numbered from one. For a multidimensional declaration, inspect the relevant bound in each dimension before designing nested loops.

Mixing character and numeric elements

Array elements must share a type. Keep text labels separate from numeric measurements. A character declaration can include the dollar sign and a length, for example array flag{3} $ 8 flag1 flag2 flag3;. Here the length belongs to newly defined character elements; it is not an instruction to convert numeric variables into strings.

For this task, the explicit visit list also keeps the numeric ID out of the transformation. A declaration using _NUMERIC_ would include previously defined numeric variables, which could make the rule act on identifiers or other measurements. Broad variable lists require a different review from the deliberately narrow list shown above.

Expecting temporary array elements in the output

A _TEMPORARY_ array holds calculation elements that are omitted from the output data set and retain their values across DATA step iterations. It is suitable for reusable constants, but a changing per-record temporary workspace needs deliberate reinitialization. Do not infer reset behavior from the word temporary.

The cleaned values in the main example need to remain visible, so they use named variables instead. An array’s local reference name, temporary calculation elements and an output variable are three different things. Decide which result must survive before choosing the declaration.

Using an array name that conflicts with a variable or function

SAS warns against function-name collisions, and the array name cannot be a variable name in the same DATA step. Use a grouping name distinct from its member variables. In the example, raw_visit names the grouping, while raw_visit1 names its first member. Braces make the indexed reference visually clear.

If the code runs but the transformation is wrong, compare the declared lists in order before changing the loop. The program pairs positions, so an accidental swap in only one list would send a correct value to the wrong cleaned column. If your actual objective is to change rows into columns or columns into rows, see PROC TRANSPOSE for reshaping SAS data; that is a separate task from applying this rule across existing columns.

Free alternatives

For a new teaching exercise, the same per-value rule can be expressed in other languages. These alternatives use their own data structures and missing-value conventions. The table compares the programming approach, rather than claiming that either runs SAS statements.

Alternative Relevant programming approach Translation decision
Base R arrays R arrays store values in a vector with a dimension attribute; a two-dimensional array is a matrix. Decide whether the visit values belong in a matrix or another object. A SAS array declaration is a grouping of variables, so the object design needs translation.
Python lists and list comprehensions A list comprehension builds a new list by applying an expression to elements, with optional filtering conditions. Preserve one output position per visit when translating this recoding rule. Filtering out a visit would change the task.

Choose the environment your collaborators can inspect and rerun. For this example, the useful acceptance check remains the same in any implementation: preserve the identifier and raw values, retain three visit positions, replace only the designated code and distinguish replacements from already-missing inputs. SAS OnDemand, described above, is also a learning route when the purpose is to practice SAS syntax itself.

Sources

Data: SAS array declaration choices for repeat-measurement preparation

An original decision table compiled from SAS statement, array training and array-function documentation. It connects declaration choices with output visibility and index handling for repeat-measurement data preparation; it is not measured performance data.

SAS array declaration choices for repeat-measurement preparation
Declaration choiceWhat it referencesOutput behaviorLoop or retention considerationSource
Explicit named numeric elementsA chosen list of numeric variablesMember variables are available in output unless excludedUse matching element order when pairing arraysSAS ARRAY Statement; Processing Variables with Arrays
Character elementsCharacter variables; $ declares character elementsNamed elements are variables, rather than the array nameSet the required length when defining new character elementsSAS ARRAY Statement
Inferred dimension with {*}The supplied one-dimensional element listOutput depends on the member variablesDIM supplies the count; * is restricted for temporary and multidimensional arraysSAS ARRAY Statement; DIM Function
Temporary elementsUnnamed calculation elementsTemporary elements are omitted from the output data setValues are retained across DATA step iterationsSAS ARRAY Statement
Explicit nondefault boundsElements indexed using the specified lower and upper limitsNamed member variables remain distinct from their subscript valuesUse LBOUND through HBOUND; DIM is the count, not the upper endpointSAS ARRAY Statement; DIM Function; LBOUND Function

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about SAS Array: Syntax, DO Loops and Worked Example

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →