Hi All,
The following SAS code creates a dataset list that contains the variable snapshot (in yyyymm format) from 200309 to 201603. There is a "if" condition that is supposed to result in only the snapshots 200309 to 201506 being populated. However, the "if" condition does not work. Please advise on why this is so. Any help would be much appreciated. Thanks!
%let strte=200309;
%let ende=201506;
%macro download;
data list(drop=i);
do i=0 to 150;
index=i;
snapshot=put(intnx('month',input("&strte.",yymmn6.),i),yymmn6.);
output;
end;
if snapshot<="&ende.";
run;
%mend download;
%download;
You must make the OUTPUT statement conditional
%let strte=200309;
%let ende=201506;
%macro download;
data list(drop=i);
do i=0 to 150;
index=i;
snapshot=put(intnx('month',input("&strte.",yymmn6.),i),yymmn6.);
if snapshot<="&ende." then output;
end;
run;
%mend download;
%download;
OUTPUT is an executable statement. You can't cancel its effect with later statements.
You must make the OUTPUT statement conditional
%let strte=200309;
%let ende=201506;
%macro download;
data list(drop=i);
do i=0 to 150;
index=i;
snapshot=put(intnx('month',input("&strte.",yymmn6.),i),yymmn6.);
if snapshot<="&ende." then output;
end;
run;
%mend download;
%download;
OUTPUT is an executable statement. You can't cancel its effect with later statements.
Why is this in a macro, there is no need for it. You can also write your code so that the do loop executes only for the number of intervals between the two items (note, if you avoided putting data in macro variables your life would also be much easier). So your code can actually be written as:
%let strte=200309; %let ende=201506; data list(drop=i); do i=0 to intck('month',input("&strte.",yymmn6.),input("&ende",yymmn6.)); index=i; snapshot=put(intnx('month',input("&strte.",yymmn6.),i),yymmn6.); output; end; run;
This will then only loop for the needed number of iterations and outputs each time, whereas the do with and if statement will run 150 times regardless of how many times it needs to.
And anothe approach with DO Until:
data list;
snapshot = input("&strte.",yymmn6.);
do until (snapshot > input("&ende",yymmn6.));
output;
snapshot= intnx('month',snapshot,1);
end;
format snapshot yymmn6.;
run;
Exercise for the interested reader to modify to a DO WHILE loop.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.