Dear SAS community,
I am having trouble counting and resetting the count with conditions and your help would be much appreciated.
Suppose that I have data below;
Subject / Year / Condition
A 1991 2
A 1992 2
A 1993 1
A 1994 2
A 1995 2
B 1990 1
B 1991 2
B 1992 1
B 1993 2
C 1991 2
C 1992 2
C 1993 2
C 1994 2
C 1995 1
I cannot change the order of this, and I would like to start counting
when first "1" appears and continue counting through "2" and reset each time "1" appears for the same individual.
so that it would give me:
A 1991 2 0
A 1992 2 0
A 1993 1 1
A 1994 2 2
A 1995 2 3
B 1990 1 1
B 1991 2 2
B 1992 1 1
B 1993 2 2
C 1991 2 0
C 1992 2 0
C 1993 2 0
C 1994 2 0
C 1995 1 1
How can I achieve this? Please help. Thank you!
Regards,
T
Here's one way:
data want;
set have;
by subject;
if first.subject then newvar=0;
if condition = 1 then newvar = 1;
else if condition = 2 then do;
if newvar then newvar + 1;
end;
run;
The condition "if newvar" will be false when NEWVAR is 0, true when it is some other integer.
Here's one way:
data want;
set have;
by subject;
if first.subject then newvar=0;
if condition = 1 then newvar = 1;
else if condition = 2 then do;
if newvar then newvar + 1;
end;
run;
The condition "if newvar" will be false when NEWVAR is 0, true when it is some other integer.
Thank you!! This works perfectly!
data have;
input Subject $ Year Condition ;
cards;
A 1991 2
A 1992 2
A 1993 1
A 1994 2
A 1995 2
B 1990 1
B 1991 2
B 1992 1
B 1993 2
C 1991 2
C 1992 2
C 1993 2
C 1994 2
C 1995 1
;
data want;
set have;
by subject;
if first.subject then want=0;
if condition=1 then want=1;
else if want then want+1;
run;
And this too! Thank you very much!
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.