Solved
New Contributor
Posts: 4

# Conditional counter

Hello everybody,

I'd like to count flag by id and order and get the "target" as below. In summary, I want to put 1 when flag is 1 and add 1 when order increases. It shouldn't change when order is same.

Could you help with solving this problem?

 id order flag target 1 1 0 0 1 1 0 0 1 2 0 0 1 2 0 0 1 2 1 1 1 3 0 2 1 3 1 1 1 4 0 2 1 4 0 2 1 5 0 3 1 5 0 3 1 6 0 4 1 6 0 4 2 1 0 0 2 1 0 0 2 2 0 0 2 2 0 0 2 2 1 1 2 3 0 2 2 3 0 2 2 4 1 1 2 4 0 1 2 5 0 2 2 5 0 2 2 5 0 2

data data01;

input id  order flag;

datalines;

1 1 0

1 1 0

1 2 0

1 2 0

1 2 1

1 3 0

1 3 1

1 4 0

1 4 0

1 5 0

1 5 0

1 6 0

1 6 0

2 1 0

2 1 0

2 2 0

2 2 0

2 2 1

2 3 0

2 3 0

2 4 1

2 4 0

2 5 0

2 5 0

2 5 0

;

run;

Accepted Solutions
Solution
‎10-26-2015 12:48 PM
Contributor
Posts: 61

## Re: Conditional counter

Try this:

``````data want;
set data01;
by id order;
if first.id then target=0;
if flag=1 then target=1;
if first.order and target>0 and flag=0 then target+1;
run;
``````

All Replies
Respected Advisor
Posts: 3,061

## Re: Conditional counter

[ Edited ]

This is untested code

` `

``````
data want;
set have;
by id order;
if first.id then target=0;
if flag=1 then target=1;
if first.order then target+1;
run;
``````

--
Paige Miller
New Contributor
Posts: 4

## Re: Conditional counter

Posted in reply to PaigeMiller
Thanks for your reply PaigeMiller but it didn't work as I wanted.
Respected Advisor
Posts: 3,061

## Re: Conditional counter

If you want further help, you have to explain further.

--
Paige Miller
Solution
‎10-26-2015 12:48 PM
Contributor
Posts: 61

## Re: Conditional counter

Try this:

``````data want;
set data01;
by id order;
if first.id then target=0;
if flag=1 then target=1;
if first.order and target>0 and flag=0 then target+1;
run;
``````
New Contributor
Posts: 4

## Re: Conditional counter

Thanks a lot ndp. it works as I want. Cheers.
Valued Guide
Posts: 864

## Re: Conditional counter

[ Edited ]

In my haste the code seems to have gotten away from me a little.  I won't be surprised to see a more elegant solution but this will work:

data want(drop=_;
set data01;
by id order;
retain _target;
if first.id and flag = 0 then do; _target = 0;target = 0;end;
if flag = 1 then do; target = 1; _target = 1;end;
if first.order and _target = 1 then target + 1;
if flag = 1 then target = 1;
run;

New Contributor
Posts: 4

## Re: Conditional counter

Posted in reply to Steelers_In_DC
it also works. Many thanks.
🔒 This topic is solved and locked.

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

Discussion stats
• 7 replies
• 403 views
• 2 likes
• 4 in conversation