How do you reference the elements of an array with more than two dimensions?


The array reference for a three-dimensional array is (depth,row,column). The array reference for a four-dimensional array is (t,depth,row,column), where t represents the fourth dimension.

The following DATA step creates an observation with 24 variables whose values are 1 through 24:

DATA in(drop=i);
ARRAY x (*) x1-x24;
DO i=1 to 24;
   x(i)=i;
   END;
RUN;
title 'The data as one observation';
PROC PRINT;

This observation loads into a three-dimensional array defined as ARRAY three_d (2,3,4) x1-x24;. It looks like this:

1 2 3 4       13 14 15 16
5 6 7 8       17 18 19 20
9 10 11 12    21 22 23 24

(1,j,k)        (2,j,k)

where j and k represent the row and column references respectively.

The following DATA step creates a three-dimensional array and outputs each element as an observation to the SAS data set md.

DATA md(keep=y);
SET in;
ARRAY three_d(2,3,4) x1-x24;
DO i=1 to 2;
   DO j=1 to 3;
     DO k=1 to 4;
     y=three_d(i,j,k);
     OUTPUT;
     END;
   END;
  END;
title 'The data as an observation for each element of the array';
PROC PRINT;
RUN;

Try commenting out one of the DO loops in the code above. The DO loop that you comment out is not processed, so you must enter a constant in the array reference. Then SAS will output all the elements for that constant value of that dimension. For example, if you comment out the 'do i=1 to 2;' statement and one of the 'end;' statements, as well as replace i with 1 in the 'y=three_d(i,j,k);' statement, SAS will output all the elements of the first matrix above:

DATA dimen_1(keep=y);
SET in;
array three_d(2,3,4) x1-x24;
DO j=1 to 3;
   DO k=1 to 4;
     y=three_d(1,j,k);
       OUTPUT;
       END;
   END;
title 'All the elements of three_d(1,j,k), where each observation is an element';
PROC PRINT;
RUN;