Hello! I am new to SAS macro and would appreciate your help.
I have the following code that I would like to put into Macro to be able to run with different parameters.
DATA myData;
set myData;
ratio1 = freq1/N1;
ratio2 = freq2/N2;
Label
ratio1 = '% Label 1'
ratio2 = '% Label 2'
;
RUN;
***************************************
I would like to create a macro function that has the following parameters:
1) Data set
2) Array of Labels (Label 1, Label 2...) with the dynamic length
So, I would like to be able to do something like:
%MACRO calculateRatio (dataSet, lbls);
DATA &dataSet;
set &dataSet;
%do i=1 %to %dim(lbls);
ratio&i =freq&i/N&i ;
%end;
Label
%do i=1 %to %dim(lbls);
ratio&i = %:_&&lbls&i;
%end;
;
RUN;
%MEND calculateRatio;
***********
%ARRAY (lbls, VALUES=Label1 Label2);
%calculateRatio (myData, lbls);
Till now – no luck. I also tried %DO_OVER(lbls,PHRASE=ratio?_I_ = ?) but keep getting tons of syntax errors. The code doesn't work and I am afraid I am doing something basically wrong. The help is highly appreciated!
Pass the list of labels as a single parameter that is delimited by some character.
%macro calculateRatio (inds,outds, labels);
%local i ;
data &outds;
set &indst;
%do i=1 %to %sysfunc(countw(&labels,|));
ratio&i =freq&i/N&i ;
label ratio&i = %sysfunc(quote(%qscan(&labels,&i,|)));
%end;
run;
%mend calculateRatio;
%calculateratio(inds=have,outds=want,labels=Label1|Label2|Label3)
You are confusing and combining ARRAY commands with MACRO commands, can't be done.
You need to use MACRO commands when you are performing macro functions. The fact that loops can be EITHER arrays or macros doesn't mean you can use array command as macro commands. There is no %dim macro command, dim is an array command. The code below assumes in &lbls you have a delimiter of backslash to separate the labels.
UNTESTED CODE
%MACRO calculateRatio (dataSet, lbls);
DATA &dataSet;
set &dataSet;
%do i=1 %to %sysfunc(countw(%superq(lbls),\));
ratio&i =freq&i/N&i ;
%end;
Label
%do i=1 %to %sysfunc(countw(%superq(lbls),\));
ratio&i = "%str(%%) %scan(&lbls,&i,\)"
%end;
;
RUN;
%MEND calculateRatio;
%calculateRatio(myData,Label 1\Label 2)
Pass the list of labels as a single parameter that is delimited by some character.
%macro calculateRatio (inds,outds, labels);
%local i ;
data &outds;
set &indst;
%do i=1 %to %sysfunc(countw(&labels,|));
ratio&i =freq&i/N&i ;
label ratio&i = %sysfunc(quote(%qscan(&labels,&i,|)));
%end;
run;
%mend calculateRatio;
%calculateratio(inds=have,outds=want,labels=Label1|Label2|Label3)
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 the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.