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;
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;
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;
If you want further help, you have to explain further.
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;
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;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.