Search code examples
sasdo-loops

Create function of two variables with do loop


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;

Solution

  • 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..