Friday, March 28, 2014

Macro tips

/* --------------- Macro 1---Input Number------------- */
%let inputRows = 8;
%let inputCols = 6;

%macro getInput(rows, cols);
data _null_;
if &rows > &cols then
do;
outStr = cats("rows=", PUT(&rows, $10.)); /* format + &var */
put outStr;
  end;
else
do;
outStr = cats("cols=", PUT(&cols, $10.));
put outStr;
end;
%mend;
%getInput(&inputRows, &inputCols);


/* ------------ Macro 2: input dataset ------------- */
/* user parameter to replace a dataset in macro */
%macro getDataset(dataset);
data _null_;
set &dataset;
if x>=y then put x=;
else put y=;
%mend;

data inputDataSet;
 input x y;
 cards;
 7 3
;
run;
%getDataset(inputDataSet);


/* ----- Macro 3---Input numeric and character and date ------------- */
%let sheetTitle = "The excel sheet title";
%let sheetID = 1;

%macro getNumCharParam(sheetTitle, sheetID);
data _null_;
if &sheetID > 2 then
do;
outStr = cats("sheet title is=", &sheetTitle); /* format + &var */
put outStr;
  end;
else
do;
outStr = cats("sheet title is=", "get nothing as id < 2");
put outStr;
end;
%mend;

%getNumCharParam(&sheetTitle, &sheetID);

/* --------  Macro 4: to return a value in dataset */
%macro macroReturnValue(inputVar, returnDataset);
data &returnDataset;
retValue = 0;
%do i=1 %to &inputVar;
retValue = retValue + 1 ;
%end;
%put retValue;
run;
%mend;

%let reapeatTimes = 1000;
%let datasetName = returnedDataSet;
%macroReturnValue(&reapeatTimes, &datasetName);
proc print data= &datasetName;
var retValue;
run;

/* Simple Macro call */
%macro xl2sas(row, col);
%put &row;
%put &col;
%mend xl2sas;
%xl2sas(3,4);

macro variables are used to store and manipulate character strings and  not the same as the DATA step variables and are stored in memory in a macro symbol table

Library references are created in order for SAS to read or write a SAS data set to a directory (or
folder). SAS calls the directory or folder a library and assigns “nicknames” to these libraries.

2. SAS® Macro Dynamics - From Simple Basics to Powerful Invocations
http://www2.sas.com/proceedings/sugi31/039-31.pdf

No comments:

Post a Comment