Wednesday, November 25, 2009

Read and sort in one step - Hash object tip

In SAS world, the classical way to process raw file is to read it into SAS dataset and then sort it. With SAS9 Hash object in DATA step, we can make an all-in-one step.

* Hash sample - read and sort raw data;
data _null_;
/* Declare hash object and key and data variable names */
if _N_ = 1 then do;
declare hash h(ordered:'A');
rc = h.defineKey('key');
rc = h.defineData('key','value');
rc = h.defineDone();
end;

/* Read key and data values */
infile datalines eof=eof;
input key value $;

/* Add key and data values to hash object */
rc = h.add();

return;
eof: rc = h.output(dataset:"ordered");
cards;
1 value1
3 value2
2 value3
;

Actually, it is only one little tip of Hash object.
We must never forget that the main functionality of Hash object is to quickly and efficiently store, search, and retrieve data based on lookup keys.

Tuesday, November 17, 2009

To list ALL using PRELOADFMT

The option PRELOADFMT is available only with Proc MEANS, Proc REPORT and Proc TABULATE.
To include all ranges and values of the user-defined formats in the output, the 3 Procs give out different usages.
Below are the samples for that.

proc format;
value $sex
'M' = 'Male' 'F' = 'Female' 'O' = 'Other';
run;

proc means data=sashelp.class completetypes mean;
format sex $sex.;
class sex / preloadfmt;
var height;
run;

proc report data=sashelp.class completerows nowd;
format sex $sex.;
column sex height;
define sex / group preloadfmt;
define height / analysis mean;
run;

proc tabulate data=sashelp.class ;
format sex $sex.;
class sex / preloadfmt;
var height;
tables sex*height*mean / printmiss;
run;

Monday, November 16, 2009

Logical expression play differently between %eval and DATA step

When programming macro, It is helpful to complete it in a DATA step and then port the code to macro. However, not all tricks in DATA step work in macro world.

Below is one tip for that:

data _null_;
do a=1 to 4;
if 1 < a < 3 then put a= "is between 1 and 3";
end;
run;

%macro test();
%put Wrong example:;
%do a=1 %to 4;
%if %eval(1 < &a < 3) %then
%put a=&a is between 1 and 3;
%end;

%put Correct example:;
%do a=1 %to 4;
%if %eval(1 < &a and &a < 3) %then
%put a=&a is between 1 and 3;
%end;
%mend;

%test()

Thursday, November 5, 2009

Get nth value of a variable

It is another idea to get nth value of a variable.


proc sort data=sashelp.class out=tmp(keep=weight)
nodupkey;
by descending weight;
run;

data _null_;
set tmp end=end;

retain weight_10th .;
if _n_ <= 10 then do;
weight_10th = weight;
end;

if end then put "The 10th weight is " weight_10th=;
run;