Help using Base SAS procedures

Resetting counter on condition

Accepted Solution Solved
Reply
Contributor
Posts: 37
Accepted Solution

Resetting counter on condition

Hi,

What can I do to reset the counter on a given condition.

Example Data;

Variable1

a

b

c

N

q

r

a

w

e

N

usually you would use _N_ to sequence but how do I get this output

a 1

b 2

c 3

N 4

q 1

r  2

a 3

w 4

e 5

N 6

How do I get it to reset. Maybe I do not understand what _N_ denotes properly. Please help. Thanks in advance.

-Akber.


Accepted Solutions
Solution
‎03-30-2012 12:39 PM
Valued Guide
Posts: 765

Re: Resetting counter on condition

hi ... another way to reset the COUNT for each new group ...

data have;

set have;

count + (-(lag(var1) eq 'N')*count) + 1;

run;  

View solution in original post


All Replies
Super Contributor
Posts: 1,636

Resetting counter on condition

how about:

data have;

input var1$;

cards;

a

b

c

N

q

r

a

w

e

N

;

data temp;

  set have;

retain count;

if lag(var1)='N' then count=1;

else count+1;

run;

proc print;run;

Super User
Super User
Posts: 6,502

Resetting counter on condition

Another method is to reset the counter on the record that marks the end of the group.  But do it AFTER writing the current count to the output dataset.

data want;

   set have;

   count+1;

   output;

   if var1='N' then count=0;

run;

Respected Advisor
Posts: 3,124

Resetting counter on condition

Another option is DOW,

data want;

do count=1 by 1  until (var1='N');

   set have;

   output;

end;

run;

Solution
‎03-30-2012 12:39 PM
Valued Guide
Posts: 765

Re: Resetting counter on condition

hi ... another way to reset the COUNT for each new group ...

data have;

set have;

count + (-(lag(var1) eq 'N')*count) + 1;

run;  

Super Contributor
Posts: 1,636

Re: Resetting counter on condition

Hi Mike,

I will go to the BASUG Q1 meeting on 4/17/2012 in Boston. Looking forward to meeting you there.

Thanks,

Linlin

Contributor
Posts: 37

Re: Resetting counter on condition

This does work but it is very inefficient. It takes hours to run on even a small dataset. Probably because it assigns the values manually.

Super User
Posts: 9,687

Re: Resetting counter on condition

data have;
input var1 $;
cards;
a
b
c
N
q
r
a
w
e
N
;
run;
data have;
 set have;
 if lag(var1) eq 'N' then count=0;
 count+1;
run;


Ksharp

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 7 replies
  • 1220 views
  • 9 likes
  • 6 in conversation