—•Today is •—

This sample uses macro logic to determine the number of unique values of a variable (the BY variable) and creates a new data set for each. The resulting data set names will be the BY variable value.


data _null_;
  set test end=eof;
  by month;
  /* On the first case of the BY-Group, */
  /* create a new macro variable VARn   */
  /* and increment the counter FLAG.    */
    if first.month then do;
      flag+1;
    call symput('var'||put(flag,8. -L),month);
    end;
  /* On the last case of the data set,  */
  /* create a macro variable to contain */
  /* the final value of FLAG.           */
    if eof then 
      call symput('tot',put(flag,8. -L));
run;
				

Create a macro to generate the new data sets using subset criteria based on the value of the BY variable. This dynamically produces data set names on the DATA statement.


%macro groups(dsn,byvar);
  data %do i=1 %to &tot;
    &&var&i;
    %end;
    set &dsn;
      %do i=1 %to &tot;
        if &byvar="&&var&i" then output &&var&i;
      %end;
  run;
%mend groups;
				

Call the macro GROUPS and specify the data set name to be split in the first macro parameter and the name of the BY variable in the second parameter.


%groups(test,month)

proc print data=jan;
  title 'January';
run;

proc print data=feb;
  title 'February';
run;
				

The use of CALL EXECUTE is to pass a parameter to a macro in order to create a new data set for each BY-Group in an existing data set. The output is identical to the output created by Example 1 above. Compile the macro BREAK. The parameter BYVAL will be generated below in the CALL EXECUTE.


%macro break(byval);
  data &byval;
    set test(where=(month="&byval"));
  run;                                                                                                                  
%mend;

/* Use the same TEST data set created */
data _null_; 
  set test;
  by month;
  if first.month
    then call execute('%break('||trim(color)||')');
run;
				

Print Document

Copyright © 2007 www.nycinformatics®.com All Rights Reserved
Last edited on: July 15, 2007
SAS product or service names are registered trademarks of SAS Institute, Inc. in the USA and other countries.
® indicates USA registration.
Source: SAS®