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; Count is the variable I am after.
ID | Flag | Count |
A | 0 | 0 |
A | 0 | 0 |
A | 1 | 1 |
A | 1 | 2 |
A | 0 | 0 |
A | 1 | 1 |
A | 1 | 2 |
B | 1 | 1 |
B | 1 | 2 |
B | 0 | 0 |
B | 1 | 1 |
B | 1 | 2 |
I need the count variable to perform as displayed above.
Whenever flag=0 the count has to reset to 0.
How can I achieve this? Please help. Thank you!
Regards,
Myu
What have you tried? Can you post the code? If not: please post the data in usable form.
Untested:
data want;
set have;
by ID;
retain count;
if first.ID then count = 0;
if Flag = 1 then Count = Count + 1;
else Count = 0;
run;
What have you tried? Can you post the code? If not: please post the data in usable form.
Untested:
data want;
set have;
by ID;
retain count;
if first.ID then count = 0;
if Flag = 1 then Count = Count + 1;
else Count = 0;
run;
data have;
input ID $ Flag;
datalines;
A 0
A 0
A 1
A 1
A 0
A 1
A 1
B 1
B 1
B 0
B 1
B 1
;
data want;
set have;
by ID;
if first.ID | flag=0 then Count=0;
if flag then Count+1;
run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.