BookmarkSubscribeRSS Feed
apple
Calcite | Level 5

Using SAS EG 7.1.

 

Basically for &LASTYEAR, the dataset with MONTHF =12 may not exist. So is there a way to ensure only the existing datasets are merged? Thank you

 


%let monlist = 06 12;

data Merged;
  set
  %do YEAR=&FIRSTYR %TO &LASTYR;
	%do i = 1 %to %sysfunc(countw(&monlist.));
    	%let monthf = %sysfunc(putn(%scan(&monlist.,&i.),z2.));
         Merged&YEAR.&MONTHF
  	%end; 
  %end;

run;
3 REPLIES 3
SASKiwi
PROC Star
%let monlist = 06 12;

data Merged;
  set
  %do YEAR=&FIRSTYR %TO &LASTYR;
	%do i = 1 %to %sysfunc(countw(&monlist.));
    	%let monthf = %sysfunc(putn(%scan(&monlist.,&i.),z2.));
        %if %sysfunc(exist(Merged&YEAR.&MONTHF.)) %then %do;
           Merged&YEAR.&MONTHF
          %end;
  	%end; 
  %end;

run;

Corrected thanks to @FreelanceReinh

Reeza
Super User

You're appending (stacking datasets) not merging. 

 

If you have the option, consider using a variable list or shortcut list instead of a macro to list the datasets.

 

For example you can can use the following to append all datasets that start with MONTH.

 

Set MONTH:;

Or you can use the following to append a series with each year and then anything that starts with Month2007, Month2008 and Month2009 will be included. 

 

Set Month2007: Month2008: Month2009:;

 

FreelanceReinh
Jade | Level 19

@apple: The SET statement needs a closing semicolon after the second %END statement.

@SASKiwi: The argument of EXIST should be Merged&YEAR.&MONTHF. Interestingly, if none of the datasets existed, the resulting "empty" SET; statement would be interpreted as SET _LAST_; and thus possibly read some random dataset.

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 1674 views
  • 2 likes
  • 4 in conversation