Help using Base SAS procedures

how to use "do loop" with skips?

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 128
Accepted Solution

how to use "do loop" with skips?

I want to do:

%DO i = 1 %to 100; but I want to skip some numbers, e.g. let said 9, and 50;

My code is:

%DO i = 1 %TO 8;

%FUNC;

%END;

%DO i = 10 %TO 49;

%FUNC;

%END;

%DO i = 51 %TO 100;

%FUNC;

%END;

Is there any way to make it more efficient? Thanks!!


Accepted Solutions
Solution
‎05-08-2014 11:50 AM
PROC Star
Posts: 1,231

Re: how to use "do loop" with skips?

Hi,

If you don't mind a %GOTO, you could do something like:

%macro loop(dummy);
  %local i;
  %do i=1 %to 100;
    %if &i=9 or &i=50 %then %goto skipped;

    %*Main code here;
    %put i=&i;

    %skipped:
  %end;
%mend loop;

%loop()


There is a popular ballotware suggestion for enhancements to macro looping, to give it more of the features of data step do loops:

https://communities.sas.com/ideas/1084

HTH,

--Q.

View solution in original post


All Replies
Solution
‎05-08-2014 11:50 AM
PROC Star
Posts: 1,231

Re: how to use "do loop" with skips?

Hi,

If you don't mind a %GOTO, you could do something like:

%macro loop(dummy);
  %local i;
  %do i=1 %to 100;
    %if &i=9 or &i=50 %then %goto skipped;

    %*Main code here;
    %put i=&i;

    %skipped:
  %end;
%mend loop;

%loop()


There is a popular ballotware suggestion for enhancements to macro looping, to give it more of the features of data step do loops:

https://communities.sas.com/ideas/1084

HTH,

--Q.

Regular Contributor
Posts: 217

Re: how to use "do loop" with skips?

%macro testit2;

%DO i = 1 %to 100;

   %if ((&i. ne %eval(9)) and (&i. ne %eval(50))) %then %do;

          %put "i = &i.";

   %end;

%END;

%mend testit2;

%testit2;

Contributor
Posts: 37

Re: how to use "do loop" with skips?

Hi Ken, I think you can give a try as below...

%DO i = 1 %TO 8, 10 %TO 100;

or

%DO i = 1 %TO 8, 10 %TO 49, 50 %TO 100;

Above code worked for me. All the Best!!

PROC Star
Posts: 1,231

Re: how to use "do loop" with skips?

pawan wrote:

Hi Ken, I think you can give a try as below...

%DO i = 1 %TO 8, 10 %TO 100;

or

%DO i = 1 %TO 8, 10 %TO 49, 50 %TO 100;

Above code worked for me. All the Best!!

Unfortunately, that sort of list works for data step DO loops, but not macro %DO loops:

16         %macro loop(dummy);
17         %do i = 1 %TO 8, 10 %TO 20;
18         %end;
19         %mend;
NOTE: The macro LOOP completed compilation without errors.
      9 instructions 184 bytes.
20         %loop()
ERROR: A character operand was found in the %EVAL function or %IF condition where a 
       numeric operand is required. The condition was: 8, 10 %TO 20 
ERROR: The %TO value of the %DO I loop is invalid.
ERROR: The macro LOOP will stop executing.


☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 238 views
  • 3 likes
  • 4 in conversation