Solved
Contributor
Posts: 37

# 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

-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;

All Replies
Super Contributor
Posts: 1,636

## Resetting counter on condition

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
Posts: 8,125

## 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;

Posts: 3,167

## 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: 10,787

## 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 and locked.