Create function of two variables with do loop

148 views Asked by At

I would like to calculate variables AR_1 to AR_99 based upon the formula

AR_(i) = 0.5*(ADM_(i) + ADM_(j)) 

where j=i+1 (ADM_1 to ADM_100 already exist in the dataset). Using the following do loop however I get an error as SAS does not recognise the variable j.

%macro do_loop;

data testdo;
set Popn99;

%do i = 1 %to 99;
  &j.=&i.+1;
  AR_&i. = 0.5 * (ADM_&i. + ADM_&j.);
%end;

run;

%mend do_loop;

%do_loop;
2

There are 2 answers

0
Allan Bowe On BEST ANSWER

try:

%macro do_loop;

data testdo;
set Popn99;

%do i = 1 %to 99;
  AR_&i. = 0.5 * (ADM_&i. + ADM_%eval(&i.+1) );
%end;

run;

%mend do_loop;

%do_loop;

Remember that SAS Macro code writes TEXT only. So the following assignment, should it have resolved (which it wouldn't as the "J" macro variable didn't exist), would have assigned a value to a "column".

  &j.=&i.+1;

That could not have then been re-used as a macro variable in the subsequent step.

To generalise - SAS Macro language writes SAS Programs (base code) which then subsequently execute to produce results..

1
Longfish On

You could also use arrays instead of a macro to achieve this.

data testdo;
set popn99;
array adm(100) adm1-adm100;
array ar(99) ar1-ar99;
do i = 1 to 99;
    ar[i] = 0.5 * (adm[i] + adm[i+1]);
end;
drop i;
run;