您的位置:首页 > 其它

first与last的组合使用

2012-08-19 23:15 141 查看
[SAS] first与last的组合使用

[前三个问题是从台湾的网站抄来的,不过为了配合说明第四个问题,我改动了原始数据]

在SAS环境里面,会使用first与last指令是很方便的事情。

因为常常会遇到要取次数、取第一笔数据、取最后一笔数据等问题,很难用SPSS去完成这样的动作(会SPSS程序语言的人很少)。

今天要介绍的这两指令的基本款使用:

先来看今天的资料:分别为ID、体重、性别、日期

1 59 1 20070101

2 62 2 20070201

2 65 2 20070301

3 65 1 20070401

3 65 2 20070501

3 65 1 20070601

问题一:如何取第一笔数据?

首先将数据汇入/输入到SAS中存成hp1为名称的数据文件,接着请注意由于first与last的用法都牵扯到依某研究者指定变项排序的过程,因此必须使用PROC SORT先进行排序动作

Data hp1;

Input id weight gender date$;

Cards;

1 59 1 20070101

2 62 2 20070201

2 65 2 20070301

3 65 1 20070401

3 65 2 20070501

3 65 1 20070601

;

Run;

Data hp2;

Set hp1;

Proc sort;

By id;

Proc print;

Run;

Data hp3first;

Set hp2;

By id;

If first.id then output;

Proc print;

run;

在此范例中依照ID进行排序后,接着我们要取第一笔数据出来。在SAS逻辑中,「if first.id then output; 」意思是如果遇到ID的第一笔请输出。接着我们看一下结果:

Obs
id
weight
gender
date
1
1
59
1
20070101
2
2
62
2
20070201
3
3
65
1
20070401
是不是就完成了?

问题二:取最后一笔数据?

我想反应快的读者已经想到是不是用「last.id」呢?没错,同理!

Data hp3last;

Set hp2;

By id;

If last.id then output;

Proc print;

run;

直接来看结果:

Obs
id
weight
gender
date
1
1
59
1
20070101
2
2
65
2
20070301
3
3
65
1
20070601
问题三:想取中间值怎么作?

照SAS逻辑想,如果first.id=0且last.id=0不就取中间值了吗?指令参照如下:

注意:如果数据没有中间值,当然就不会取出来喔!

Data hp3middle;

Set hp2;

By id;

If first.id=0 and last.id=0;

Proc print;

Run;

注意只有第5条数据符合结果:

Obs
id
weight
gender
date
1
3
65
2
20070501
如果我想计算次数该怎么作呢?

这时候我们就要创一个变项来放计算后的次数,本范例创「c」这个变项,先告诉SAS说当遇到第一笔数据时请让「c=.」,接着我让「c+1」意思是随着数据一笔扫过去请加1,最后至少要有终结啊!就让SAS遇到最后一笔数据时候停止。

Data fre;
Set hp2;
By id;
If first.id=1 then c=.;
C+1;
If last.id=1;
Proc print;

Run;

结果:

Obs
id
weight
gender
date
c
1
1
59
1
20070101
1
2
2
65
2
20070301
2
3
3
65
1
20070601
3
因此结果就变成每个个案后面都有一个次数,不就完成了吗 : ) 不过其实过程中特别要注意Output的位置摆放,下回SAS特辑待续。

问题四:first与last的组合使用

如果使用两个变量排序呢

把问题一的程序修改一下:

Data hp5first;

Set hp2;

By id weight;

If first. weight then output;

Proc print;

run;

Obs
id
weight
gender
date
1
1
59
1
20070101
2
2
62
2
20070201
3
2
65
2
20070301
4
3
65
1
20070401
问题二修改:

Data hp5last;

Set hp2;

By id weight;

If last.weight then output;

Proc print;

run;

结果:

Obs
id
weight
gender
date
1
1
59
1
20070101
2
2
62
2
20070201
3
2
65
2
20070301
4
3
65
1
20070601
问题三修改:

Data hp3middle;

Set hp2;

By id weight;

If first. weight =0 and last. weight =0;

Proc print;

Run;

Obs
id
weight
gender
date
1
3
65
2
20070501
综合来看,使用两个by变量时,第二个变量的first和last值受第一个变量的影响。

From:http://blog.sina.com.cn/s/blog_4a17fc5b01015rmr.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: