Margaret
Margaret

Reputation: 1

sas macro do loop and ampersand to subset dataset

In the macro below, how do I automate selecting cars from sashelp.cars in my data step. I think it involves ampersands %let dsn = &inDsn; ....

       %macro subset_by_make (dsn=,carList=);

    %let car_n = %sysfunc(countw(&carList, ' '));

    %do i = 1 %to &car_n;
    %let make = %scan (&carList, &i, ' ');
    data cars_&make;
        set sashelp.cars(where = (make = "&make"));
    run;
    proc print data=cars_&make;
    run;
%end;
 %mend subset_by_make;
 %subset_by_make(dsn=sashelp.cars, carList= Acura Toyota);

Would appreciate any help Maggie

Upvotes: 0

Views: 170

Answers (2)

Margaret
Margaret

Reputation: 1

Reeza, sorry my question is confusing. I wanted to create various datasets called cars_acura, cars_toyota, etc. from sashelp.cars

Below, I think I have found a solution. Thanks everyone for your help!

%macro subset_by_make (lib=,inDsn=,carList=);

    %let car_n = %sysfunc(countw(&carList, ' '));

    %do i = 1 %to &car_n %by 1;
        %let make = %scan (&carList, &i, ' ');      
      title "dataset: &inDsn._&make";
        data &inDsn._&make;
            set &lib..&inDsn(where = (make = "&make"));
        run;
        proc print data=cars_&make;
        run;
    %end;
%mend subset_by_make;
%subset_by_make(lib=sashelp,inDsn=cars,carList= Acura Toyota);

Upvotes: 0

user667489
user667489

Reputation: 9569

There's no need for any macro code at all here if all you want to do is print out the cars dataset grouped by make:

proc sort data = sashelp.cars out = cars;
by make;
run;

proc print data = cars;
where make in ('Acura','Toyota');
by make;
run;

Upvotes: 1

Related Questions