BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
tonoplast
Obsidian | Level 7

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

1 ACCEPTED SOLUTION

Accepted Solutions
Astounding
PROC Star

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.

View solution in original post

4 REPLIES 4
Astounding
PROC Star

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.

tonoplast
Obsidian | Level 7

Thank you!! This works perfectly!

novinosrin
Tourmaline | Level 20

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;
tonoplast
Obsidian | Level 7

And this too! Thank you very much!