在SAS编程中,使用Hash对象能够快速的进行检索和匹配,减少程序运行时间,对项目后期Batch Run检查程序Log有重要意义。

在SAS编程中使用Hash对象

声明和定义

hash对象应用的初始步骤是先声明对象,然后定义key和data。

data a;
    if _N_ = 1 then do;
        declare hash h();
        rc = h.definekey('k');
        rc = h.defineData('d');
        rc = defineDone();
        call missing(k, d);
    end;
run;
  • 这两种声明方式都可以:

    • declare hash myhash(dataset: 'mydata', ordered: 'yes');

    • myhash = _new_ hash(dataset: 'mydata', ordered: 'yes');

  • 如果需要选择多列,可以这样定义:h.defineData(Multidata:'yes')

  • call missing可以避免未初始化的报错。

储存和检索

在声明和定义之后,就可以用findfind_nextfind_prevadd等方法进行数据储存和检索。

官方案例

使用addfind函数储存和检索数据:

data _null_;
length d $20;
length k $20;

/* Declare the hash object and key and data variables */
if _N_ = 1 then do;
   declare hash h();
   rc = h.defineKey('k');
   rc = h.defineData('d');
   rc = h.defineDone();
end;

/* Define constant value for key and data */
k = 'Homer';
d = 'Odyssey';
/* Use the ADD method to add the key and data to the hash object */
rc =h.add();
if (rc ne 0) then
   put 'Add failed.';

/* Define constant value for key and data */
k = 'Joyce';
d = 'Ulysses';
/* Use the ADD method to add the key and data to the hash object */
rc = h.add();
if (rc ne 0) then
   put 'Add failed.';

k = 'Homer';
/* Use the FIND method to retrieve the data associated with 'Homer' key */
rc = h.find();
if (rc = 0) then
   put d=;
else
   put 'Key Homer not found.';
run;

简单来说操作就是用add函数添加了观测1:k = 'Homer'; d = 'Odyssey';,然后添加了观测2:k = 'Joyce'; d = 'Ulysses';,然后再用find进行检索,如果存在观测就将其put出来。

因为hash对象是添加到内存里的,所以添加两条数据之后,如果把数据存到work库里看,只能看到最后一条数据,必须用output才能把key和data输出来,或者用h.output()才能直接输出data。