Tuesday, June 21, 2016

SAS: Looping through an array with DO OVER



A “legacy” programmer can get the job done, but not always in the most efficient way.

No one ever sends the “legacy” guys to training.

Hence this blog, as I attempt to record new (to me) tricks this old dog has learned.

Here’s one: using “do over” to loop through a SAS array.

Source code:

* demonstrate do over for looping through array ;

data work.my_array;
prime1 = 2; prime2 = 3; prime3 = 5; prime4 = 7; prime5 = 11;
run;

data _null_;
set work.my_array;
array primes prime1-prime5;
sum = 0;
do over primes;
     put primes=;
     sum = sum + primes;
end;
put sum=;
run;


Log:

1    * demonstrate do over for looping through array ;
2
3    data work.my_array;
4    prime1 = 2; prime2 = 3; prime3 = 5; prime4 = 7; prime5 = 11;
5    run;

NOTE: The data set WORK.MY_ARRAY has 1 observations and 5 variables.
NOTE: DATA statement used (Total process time):
      real time           0.04 seconds
      cpu time            0.04 seconds


6
7    data _null_;
8    set work.my_array;
9    array primes prime1-prime5;
10   sum = 0;
11   do over primes;
12       put primes=;
13       sum = sum + primes;
14   end;
15   put sum=;
16   run;

prime1=2
prime2=3
prime3=5
prime4=7
prime5=11
sum=28
NOTE: There were 1 observations read from the data set WORK.MY_ARRAY.
NOTE: DATA statement used (Total process time):
      real time           0.05 seconds
      cpu time            0.06 seconds

No comments:

Post a Comment