BookmarkSubscribeRSS Feed
deleted_user
Not applicable
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);
1 REPLY 1
deleted_user
Not applicable
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

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 1 reply
  • 815 views
  • 0 likes
  • 1 in conversation