使用SAS计算多个变量中的行 [英] Counting rows in multiple variables using SAS
问题描述
我有一个问题使用SAS创建计数变量。
I have a question in creating a count variable using SAS.
Q R
----
1 a
1 a
1 b
1 b
1 b
2 a
3 a
3 c
4 c
4 c
4 c
我需要创建一个变量S来计算具有相同Q和R组合的行。将是输出。
I need to create a variable S that counts the rows that has same combination of Q and R. The following will be the output.
Q R S
-------------------
1 a 1
1 a 2
1 b 1
1 b 2
1 b 3*
2 a 1
3 a 1
3 c 1
4 b 1
4 b 2
4 b 3
我尝试使用以下程序:
数据二;
设置一个;
S + 1;
by QR;
如果first.Q和first.R,则S = 1;
运行;
data two;
set one;
S + 1;
by Q R;
if first.Q and first.R then S = 1;
run;
但是,这没有正确运行。例如,*将显示为1而不是3.我将感谢任何关于如何使此计数变量正常工作的提示。
But, this did not run correctly. For example, * will come out as 1 instead of 3. I would appreciate any tips on how to make this counting variable work correctly.
推荐答案
很接近,你的if语句应该是first.R(或更改和为OR,但是这不是有效的)。我通常喜欢在设置为1后增量。
Very close, your if statement is should be first.R (or change the and to OR but that isn't efficient). I usually prefer to have the increment after the set to 1.
data two;
set one;
by Q R;
*Retain S; *implicitly retained by using the +1 notation;
if first.R then S = 1;
else S+1;
run;
这篇关于使用SAS计算多个变量中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!