Search code examples
macrossasdo-loopssas-studio

SAS - Do looping from condition1 to condition2


I am looking to have a programme which cleans up some messy data I have, I am looking to do this for both the assets and liabilities side of the project i'm working on.

My question is there a way to use a do loop to use the cleaning up data to first clean up the assets then liabilities. something like this:

%do %I = Asset %to Liability;

%assetorliability= I ;

proc sort data = &assetorliability;
by price;
run;

data want&assetorliability;
set &assetorliability;
if _N_ < 50000;
run;

the actual script is quite long so a singular macro may not be the ideal solution but this loop would be great.

TIA.

EDIT : the programme includes some macros and the errors received are as follows:

%let list =Asset Liability;
%do i=1 %to %sysfunc(countw(&list,%str( )));

%let next=%scan(&list,&i,%str( ));

%Balance;

%end;

in the macro the data steps are named with a balance&list to allow for each scenario. the errors are:

13221  %let list =Asset Liability;
13222  %do i=1 %to %sysfunc(countw(&list,%str( )));
ERROR: The %DO statement is not valid in open code.
13223
13224  %let next=%scan(&list,&i,%str( ));
WARNING: Apparent symbolic reference I not resolved.
WARNING: Apparent symbolic reference I not resolved.
ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric
       operand is required. The condition was: &i
ERROR: Argument 2 to macro function %SCAN is not a number.
ERROR: The %END statement is not valid in open code.

Solution

  • The macro %do statement is not as flexible as the data step do statement. To loop over a list of values you would want to put the list into a macro variable and use an index variable in your %do loop.

    Note that macro logic needs to be inside of a macro. You cannot use it in "open" code.

    %macro do_over(list);
    %local i next;
    %do i=1 %to %sysfunc(countw(&list,%str( )));
      %let next=%scan(&list,&i,%str( ));
      proc sort data = &next ;
        by price;
      run;
    
      data want&next ;
      ...
    %end;
    %mend do_over ;
    %do_over(Asset Liability)