DATA Step, Macro, Functions and more

Using DO and END outside of a datastep??

Reply
N/A
Posts: 0

Using DO and END outside of a datastep??

I'm trying to run a piece of code X number of times returning a separate dataset for the last X months. Can I use do, to and end outside of the datastep, but inside a macro? It doesn't seem to work.



%macro test(period);

%do i=1 %to .

data _null_;
call symput ('position', i);
run;

%let posdate=INTnx('MONTH',today(),-&position);

data pos&position;
set inputdata;
where timeid=&posdate;
run;

proc sort data=pos&position;
by accountid;
run;

%end;

%mend;

%test(12);
N/A
Posts: 0

Re: Using DO and END outside of a datastep??

cstayner,

You're nearly there. I'd make a few changes:

Your null data step is the right idea, but I'd avoid adding a variable that doubles up on i, you could get the data step doing some work, and move the posdate calculation here:

data _null_;
call symput ('posdate', INTnx('MONTH',today(),-&i));
run;

This would be quite a bit better - the way you have written the posdate assignment will have problems because the intnx() and today() functions are not macro functions. The alternative would be:

%let posdate=%sysfunc(INTnx('MONTH',%sysfunc(today()),-&position));

In this case I'd be inclined, though, to restructure the code, see below:

data have(keep=account_id time_id);
do t = 0 to 11;
do account_id = 12 to 1 by -1;
time_id = intnx('month', '01Jan2008'd, t);
output;
end;
end;
run;

%macro sortseg(months=12);

proc sort
data = have
;
by account_id
;
run;

/* Create the macro variables we want, one set for months, one for datasets */
data _null_;
do m = 1 to &months;
call symput('month_'||compress(m), compress(intnx('month', '01Jan2009'd, -m)));
call symput('ds_out_'||compress(m), 'want_'||compress(m));;
end;
run;
/* Specify multiple output datasets */
data
%do month_loop = 1 %to &months;
&&ds_out_&month_loop
%end;
;
set have;
/* Use if, rather than where, to conditionally output */
%do month_loop = 1 %to &months;
if time_id = &&month_&month_loop then output &&ds_out_&month_loop;
%end;
run;

%mend;

%sortseg(months=12)

The macro code is writing the SAS code, rather than executing the process, and this is one of the key things to remember about how macro and SAS code interact.

I hope this helps,

ProcMe
Ask a Question
Discussion stats
  • 1 reply
  • 120 views
  • 0 likes
  • 1 in conversation