3
votes

Is there any form to keep variables with a doop loop in data step? will be something as:

data test;
input id aper_f_201501 aper_f_201502 aper_f_201503 aper_f_201504 
aper_f_201505 aper_f_201506;
datalines;
1 0 1 2 3 5 7
2 -1 5 4 8 7 9
;
run;

%macro test;
%let date = '01Jul2015'd;

data test2;
set test(keep=do i = 1 to 3;
                 aper_f_%sysfunc(intnx(month,&date,-i,begin),yymmn6.);
              end;)
run;
%mend;
%test;

I need to iterate several dates. Thank you very much.

2
No, but you can use shortcut references if you have a common prefix. - Reeza

2 Answers

3
votes

You need to use macro %do loop instead of the data step do loop, which is not going to be valid in the middle of a dataset option. Also do not generate those extra semi-colons into the middle of your dataset options. And do include a semi-colon to end your SET statement.

%macro test;
%local i date;
%let date = '01Jul2015'd;

data test2;
  set test(keep=
%do i = 1 %to 3;
  aper_f_%sysfunc(intnx(month,&date,-i,begin),yymmn6.)
%end;
  );
run;
%mend;
%test;
1
votes

You can use the colon shortcut to reference variables with the same prefix, anything in front of the colon will be kept.

keep ID aper_f_2015: ;

There's also a hyphen when you have sequential lists

keep ID aper_f_201501-aper_f_201512;

You can use a macro but not sure it adds a lot of value here.