Hello there,
I would appreciate if you could help me to calculate the number of consecutives occurences.
Here is an example
Have
ID | Group |
1 | 0 |
2 | 1 |
3 | 0 |
4 | 1 |
5 | 1 |
6 | 0 |
7 | 0 |
Want
ID | Group | Count |
1 | 0 | 0 |
2 | 1 | 1 |
3 | 0 | 0 |
4 | 1 | 2 |
5 | 1 | 2 |
6 | 0 | 0 |
7 | 0 | 0 |
Thanks in advance!
Here's an approach:
data want;
counter = 0;
do until (last.group);
set have;
by group notsorted;
counter + 1;
end;
do until (last.group);
set have;
by group notsorted;
if group = 0 then count = 0;
else count = counter;
output;
end;
drop counter;
run;
It's untested code, so you will have to try it to see if it needs any adjustments.
Here's an approach:
data want;
counter = 0;
do until (last.group);
set have;
by group notsorted;
counter + 1;
end;
do until (last.group);
set have;
by group notsorted;
if group = 0 then count = 0;
else count = counter;
output;
end;
drop counter;
run;
It's untested code, so you will have to try it to see if it needs any adjustments.
Thanks a lot! I tested it and it works fine.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.