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

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. 

IDFlagCount
A

0

0
A

0

0

A11
A12
A

0

0
A11
A12
B11
B12
B00
B11
B12

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

1 ACCEPTED SOLUTION

Accepted Solutions
andreas_lds
Jade | Level 19

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;

View solution in original post

3 REPLIES 3
andreas_lds
Jade | Level 19

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;
Myurathan
Quartz | Level 8
You are a real saviour. Thank you so much.
PeterClemmensen
Tourmaline | Level 20
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;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 2316 views
  • 0 likes
  • 3 in conversation