DATA Step, Macro, Functions and more

Is there a way to loop through a series of like parameters?

Reply
Valued Guide
Posts: 610

Is there a way to loop through a series of like parameters?


%macro combineYears(Year1, Year2, Year3, Year4, Year5);

do year1 to year5;

/*process logic*/

end;
%end;

Super User
Posts: 6,644

Re: Is there a way to loop through a series of like parameters?

Posted in reply to DavidPhillips2

Yes, but it would be easier if you get rid of the commas between the values.  Here's some documentation:

 

https://blogs.sas.com/content/sastraining/2015/01/30/sas-authors-tip-getting-the-macro-language-to-p...

 

 

Super User
Posts: 23,357

Re: Is there a way to loop through a series of like parameters?

Posted in reply to DavidPhillips2

 Depends on how you want to use it. You may end up finding that a %DO loop may work just as well. 

 

You can also check out examples  3 and 4 here:

https://communities.sas.com/t5/SAS-Communities-Library/SAS-9-4-Macro-Language-Reference-Has-a-New-Ap...

 

 

Frequent Contributor
Posts: 109

Re: Is there a way to loop through a series of like parameters?

Posted in reply to DavidPhillips2

It can be done as follows.

%macro combineYears(Year1, Year2, Year3, Year4, Year5);
%do i=1 %to 5;
	%put year= &&year&i;
	/*process logic*/
%end;
%mend combineYears;

%combineYears(2000, 2001, 2010, 2015, 2018);


*LOG

year= 2000
year= 2001
year= 2010
year= 2015
year= 2018

It will be good if you also pass the number of years you are passing and use to loop control.

 

Please let us know if it helped. 

Super User
Posts: 13,358

Re: Is there a way to loop through a series of like parameters?

Posted in reply to Satish_Parida

@Satish_Parida your approach, while it will work would have issues if the user only wants to process 2 years and would require a diffent macro to process any different number of year.

 

This is what @Astounding meant by getting rid of commas:

%macro combineYears(YearList);
%do i=1 %to %sysfunc(countw(&yearlist));
	%put year= %scan(&yearlist,&i);
  
	/*process logic*/
%end;
%mend combineYears;

%combineYears(2000 2001 2010 2015 2018);

which will process any explicit list of one or more items. Note that we have no check for and empty list though nothing inside the %do loop will happen so likely okay for that, or checks to ensure that the values in the list are valid for any other purpose.

 

Ask a Question
Discussion stats
  • 4 replies
  • 137 views
  • 0 likes
  • 5 in conversation