[英]Assigning numbers to items in a loop — SAS
Each ID number has several items associated with it. 每个ID号都有几个与之关联的项目。 For every item under each ID, I want to assign a number to it.
对于每个ID下的每个项目,我想为其分配一个数字。 I would like the number to start at 1 for each ID.
我希望每个ID的数字都从1开始。 How would I do this in SAS?
我将如何在SAS中执行此操作? I'm guessing I can use a type of loop statement.
我猜我可以使用一种循环语句。 Below is an example of my goal.
以下是我目标的一个示例。 Thanks for your help.
谢谢你的帮助。
EDIT: I have to add another layer to this problem. 编辑:我必须向此问题添加另一层。 If the ID has item = SPECIAL, I want that record to always be assigned 1 and have the other items follow it.
如果ID的项= SPECIAL,则我希望该记录始终被分配为1,并让其他项紧随其后。
+----+----------+----------+
|ID |Item |Assignment|
+----+----------+----------+
|A001|SPECIAL |1 |
+----+----------+----------+
|A001|Orange |2 |
+----+----------+----------+
|A001|Pineapple |3 |
+----+----------+----------+
|A002|Banana |1 |
+----+----------+----------+
|A002|Strawberry|2 |
+----+----------+----------+
|A002|Pear |3 |
+----+----------+----------+
|A002|Watermelon|4 |
+----+----------+----------+
|A003|SPECIAL |1 |
+----+----------+----------+
|A003|Banana |2 |
+----+----------+----------+
|A003|Apple |3 |
+----+----------+----------+
The easiest way to do it - with BY statement and automatic variables FIRST and LAST. 最简单的方法-使用BY语句以及自动变量FIRST和LAST。 Original dataset should be sorted by ID before.
原始数据集之前应按ID排序。
data have;
input ID $ Item $;
datalines;
A001 SPECIAL
A001 Orange
A001 Pineapple
A002 Banana
A002 Strawberry
A002 Pear
A002 Watermelon
A003 SPECIAL
A003 Banana
A003 Apple
;
run;
data want;
set have;
by ID;
if FIRST.ID then Assignment=1;
else Assignment+1;
run;
Regarding your additional layer: just add one more condition to the IF-statement: 关于您的附加层:只需在IF语句中再添加一个条件:
`if FIRST.ID or item='SPECIAL' then Assignment=1;`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.