Hello everyone,
I am working to improve my knowledge of macro usage. My question is, is it possible to perform the same data step on three different datasets at one time using a macro as opposed to writing out the data step three different times. I know I can combine the datasets and perform the data step only once but I would like to explore macro options. My sample data is as follows:
data fruit_1;
length FRUIT $10.;
input FRUIT $ TOTAL;
datalines;
Orange 2
Grape 31
Strawberry 5
;
run;
data fruit_2;
length FRUIT $10.;
input FRUIT $ TOTAL;
datalines;
Cherry 20
Lemon 15
Pineapple 4
;
run;
data fruit_3;
length FRUIT $10.;
input FRUIT $ TOTAL;
datalines;
Apricot 12
Plum 5
Kiwi 16
;
run;
I would like to run a datastep like below on all of the above datasets without having to rewrite the datastep two additional times.
data fruit_1;
set fruit_1;
if total ge 5 then OVER = 1;
else OVER = 0;
run;
You have done the first step of macro writing, which is to create code that works for one situation without macros. Congratulations, most people don't do this step!
Then you insert macro language into this working code, which loops over all 3 data sets. In this case, the only thing that changes is the number after FRUIT_, so this is the only place that the loop will make changes.
%macro dothis;
%do i=1 %to 3;
data fruit_&i;
set fruit_&i;
if total ge 5 then OVER = 1;
else OVER = 0;
run;
%end;
%mend;
%dothis
You have done the first step of macro writing, which is to create code that works for one situation without macros. Congratulations, most people don't do this step!
Then you insert macro language into this working code, which loops over all 3 data sets. In this case, the only thing that changes is the number after FRUIT_, so this is the only place that the loop will make changes.
%macro dothis;
%do i=1 %to 3;
data fruit_&i;
set fruit_&i;
if total ge 5 then OVER = 1;
else OVER = 0;
run;
%end;
%mend;
%dothis
Thank you so much!
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.