【SAS】学习笔记——索引(index)篇

索引【INDEX】

一、基本含义

是对数据集观测进行操作的强有力工具。

索引可以帮助你快速定位一条或多条你想要读取的符合特定条件的观测。

在没有索引的情况下,SAS是一条接一条的扫描观测;有索引时,直接跳到该索引对应的观测所在位置。总结一句话就是:节省时间,节省内存,提高效率。

当然并不是任何情况下使用索引都能提高工作效率,因为建立索引本身需要耗费内存,是否使用索引,要视具体情况而定。

索引分为简单索引【simple index】和复合索引【composite index】

简单索引由单个变量的值组成,字符变量或数值变量都可以。SAS会自动给简单索引命名为跟相应变量一样的名字。

复合索引由多个关键变量的值连接而成。复合变量的名字不能与任一已建立的索引重名。

二、创建索引的方法

(一)data步创建

DATA  sas-data-file-name(index=);

例1.1 DATA步创建简单索引

DATA class (index=studentID);

run;

也可以创建多个简单索引

DATA class (index=studentID firstname);

run;

可以再加上unique选项

DATA class (index=studentID/unique firstname);     *studentID为unique索引,而firstname不是,也可以在其后面加上unique,(firstname/unique)使其也成为unique 索引。

run;

创建复合索引

DATA class (index=(IDNAME=studentID firstname));  *IDNAME是复合索引的名字。后面仍然可以使用unique。

run;

(二)PROC DATASETS过程创建

PROC DATASETS library=<libref>;

            modify <dataset>;

           index create <variable>;

quit;

例2.1 

PROC DATASETS library=work;

                       modify class;

                      index create studentID ;

                      index create firstname;

                      index create IDNAME=(studentID firstname);

quit;

在PROC DATASETS中删除索引用 index delete 语句;

例2.2,在例2.1的基础上进行删除

PROC DATASETS library=work;;

             modify class;

              index delete studentID;

             index delete firstname;

             index delete IDNAME;

quit;

PROC DATASETS executes statements in order. Therefore, if you are deleting and creating indexes in the same step, you should delete indexes first so that the newly
created indexes can reuse space of the deleted indexes.
(三)在PROC SQL中创建索引

PROC SQL;

             create <unique> index <indexname> on   <tablename(colname)>; *unique 可选

quit;

例3.1 

PROC SQL;

            create unique index studentID on class(studentID);

 quit;

PROC SQL ;

            create index IDNAME on class(studentID,firtname);

quit;

删除用DROP。

PROC SQL;

            drop index studentID from class;

quit;

三、索引的使用情况

我们可以更改一个系统设置以观察索引是否被使用

options msglevel=i;    在这个设置下,SAS日志里会给出索引是否被使用的信息。系统默认的设置是msglevel=n。

在以下情况下,索引不会被使用

1.在DATA步的IF子句中       如: DATA newclass;set class; if studentID=“c0001”;run;

2.在特殊的where句中         如:DATA newclass; set class; where studentID ne “c001”;run;

3.SAS判定不使用索引更高效时。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值