Conditional counter

Accepted Solution Solved
Reply
New Contributor
Posts: 4
Accepted Solution

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? 

 

 

idorderflagtarget
1100
1100
1200
1200
1211
1302
1311
1402
1402
1503
1503
1604
1604
2100
2100
2200
2200
2211
2302
2302
2411
2401
2502
2502
2502

 

 

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

View solution in original post


All Replies
Trusted Advisor
Posts: 1,931

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;

 

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.
Trusted Advisor
Posts: 1,931

Re: Conditional counter

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

Solution
‎10-26-2015 12:48 PM
Contributor ndp
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: 860

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=_Smiley Happy;
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
  • 370 views
  • 2 likes
  • 4 in conversation