Search code examples
loopssasmacrosfrequency

SAS Macro to iterate proc freq using a list


I have a dataset where I have to run frequencies on a dozen variables for a dozen organizations. This is very easy with proc print but I don't want to have to update the WHERE statement a dozen times to run each of the frequencies so I am hoping to simplify this with a macro.

As an example, we can use the sashelp.cars dataset where it runs a frequency for two variables (for simplicity) by each auto maker.

I wrote a macro hoping to iterate a simple proc freq like the following except the macro would iterate through the list of auto makers "make" in the WHERE statement and run the assigned frequencies.

proc freq data=sashelp.cars; 
    table Type DriveTrain;
    where make = "Honda";
run;

Here is the macro I wrote:

%macro car_freq(dataset, n_make);
    %do i = 1 %to &n_make;
        %let maker =  %scan(make., &i);

        title "&maker";
    proc freq data=&dataset;
        where make = "&maker";
        tables type DriveTrain;
    run;
title;
%end;
%mend car_freq;

%car_freq(sashelp.cars, 38)

When I run the macro, it runs without errors but says that there are 0 observations for each iteration. What am I missing to get this to iterate through the list of makers and run the frequencies for the two variables?


Solution

  • You can Sort the data and use BY statement.

    proc sort data=sashelp.cars out=cars;
      by make;
    run;
    
    ods html file='report.html';
    
      options byline;
      title;
      proc freq data=cars;
        by make;
        tables type drivetrain;
        where make in: ('L');
      run; 
    
    ods html close;
    

    Will output

    enter image description here