Hi everyone,
I need to filter a data set several times and execute a specific proc in each one (that proc not support the by statement). I'm trying to write a do macro which goes over specific values (that I would use to filter the data and execute the proc). I tried the following code:
%macro loop(values);
let count=%sysfunc(countw(&values));
%do i = 1 %to &count;
%let value=%qscan(&values,&i,%str(,));
%put &value;
data B_&values;
set A;
where id = i;
run;
%end
%mend
%loop(%str(1,2,3))
I intended to get as a result 3 data sets (B_1, B_2 and B_3) which I would use to execute my proc (inside the do loop). But it isn't working.
Someone can help?
Thanks.
Is this the same question as this:
https://communities.sas.com/t5/Base-SAS-Programming/Macro-filter/m-p/488359
Mainly because you are not testing macro variable but some (possible non-existant) dataset variable named I. Do you want the records where ID = &I ? Or where ID = &value ?
You have other typos in the program also.
You also do not want to use %qscan() to macro quote the value since you are using it as part of a dataset name there cannot be anything in it that would need macro quoting. And the macro quoting might cause issues with SAS parsing the generated code
.
It is also a lot easier to use a space as the delimiter instead of a comma since then it means you don't need to macro quote the call.
Make sure to define your macro variables as local, in case the calling environment is using any of those macro variable names already.
%macro loop(values);
%local i count value;
%let count=%sysfunc(countw(&values,%str( )));
%do i = 1 %to &count;
%let value=%scan(&values,&i,%str( ));
%put &value;
data B_&value;
set A;
where id = &i;
run;
%end
%mend loop;
%loop(1 2 3);
In general, looping of this sort is not a good programming method in SAS. Rather than create many individual data sets by ID, most programming is much easier in SAS leaving everything in one large data set and then using BY statements in your analysis.
Is this the same question as this:
https://communities.sas.com/t5/Base-SAS-Programming/Macro-filter/m-p/488359
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
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.