Pruthvi
Pruthvi

Reputation: 31

Creating a macro to create dummy variables for categorical variables in my data set sas

I have written the following SAS code to create dummy variables for all my categorical variables. However the code does not see to give me a desired result.

/# creating a copy of the data set in the work library#/

  libname eco "Z:\Globe\Call Data Modeling";
   data model_data;
   set eco.em_save_train;
   run;

/#getting the names and types of variables in the data set

proc contents data= model_data out= var_names(keep=name type)noprint;
   run;

/#creating a macro to create the dummy variable coding#/

 %macro cat(indata, variable);
  proc sql noprint;
    select distinct &variable. into :mvals separated by '|'
    from &indata.;

    %let mdim=&sqlobs;
  quit;

  data &indata.;
    set &indata.;
    %do _i=1 %to &mdim.;
      %let _v = %scan(&mvals., &_i., |);
      if &variable. = &_v. then &variable.&_v. = 1; else &variable.&_v = 0;
    %end;
  run;
%mend;

/#calling the macro and passing the dataset name and variable name, based on the type . if type=2 then it is categorical variable#/

data _null_;
set var_names;
if type=2 then call execute('%cat(model_data,'||name||')');
run;

Upvotes: 0

Views: 987

Answers (2)

data _null_
data _null_

Reputation: 9109

I would not recommend using a macro and data steps for this. SAS has great solutions that do all the heavy lifting. Easy and well documented.

data nominal;
    infile datalines dsd;
    input hair$ eye$;
datalines;
brown,brown
brown,blue
red,blue
red,brown
;;;;

proc transreg design;
   model class(hair eye / zero=none);
   output out=dummies(drop=_: intercept);
   run;
%put NOTE: Dummies: &=_TRGINDN &=_TRGIND;
proc print;
   run;

enter image description here

Upvotes: 2

Andrew
Andrew

Reputation: 1618

See the post Dummy Coding Variables in SAS

Upvotes: 0

Related Questions