Tuesday, May 23, 2017

SAS Macro – Slider (SAS)

Though not included as a part of our initial example set, there will be instances while working with data, where, for cosmetic purposes, you may want to move data variables from the right side of the data set, to the left side of the data set. This can only be achieved if the data values which are being consolidated are of the same data type.

Example Set:


To consolidate variables to the leftmost portion of the data set to eliminate blank variable columns, run the following macro code:

%MACRO SLIDERA;
%do e = 1 %to 4; /* Number of variable columns which need to be consolidated. */
%let y = %eval(&e+1); /* Number of variable columns that need to consolidated plus 1. */

/* Modify the values below to match the data variables of your non-sample set. It is important that variable names are listed in sequential order from left to right. Ex. VAR | VAR1 | VAR2 | VAR3 | etc.*/

If DATAVAL = "" then
do;
if DATAVAL NE "" then
do;
DATAVAL = DATAVAL1;
DATAVAL1 = "";
end;
end;

If DATAVAL&e = "" then
do;
if DATAVAL&y NE "" then
do;
DATAVAL&e = DATAVAL&y;
DATAVAL&y = "";
end;
end;

%end;

%mend;

This code will need to be run once for each movement left that is made per variable. This is achieved as an aspect of the next macro. I would recommend assigning whatever variable value that was initially assigned to variable ‘e’ in the macro above, to the variable value of‘f’ in the macro below.


%MACRO SLIDERB;

%do f = 1 %to 4;

Data SETA ; /* The name of your data set. */
Set SETA ; /* The name of your data set. */

%SLIDERA;

Run;

%end;

%mend;

Now run the macro 'SLIDERB'.

%SLIDERB;

The macro ‘SLIDERB’ contains the macro ‘SLIDERA’. When initialized, ‘SLIDERB’ runs the ‘SLIDERA’ macro a total of 4 times. Each time the macro ‘SLIDERB’ loops, it overwrites the previous data set. In doing so, it moves each value over one time, and then in looping, it re-initializes the process of moving each variable value over again. The final set should resemble:


Given the size of certain data sets and the amount of variables that they may contain, running this particular set of macros may be more efficient if run over-night. I would always recommend copying the initial set that you wish to modify before utilizing this macro.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.