to find all numbers that appear at least three times consecutively with data step.
data have;input Id num ;
cards;
1 1
2 1
3 1
4 2
5 1
6 2
7 2
;
Id | Num |
1 | 1 |
2 | 1 |
3 | 1 |
4 | 2 |
5 | 1 |
6 | 2 |
7 | 2 |
+-----------------+For example, given the above Logs
table, 1
is the only number that appears consecutively for at least three times.
| ConsecutiveNums | +-----------------+ | 1 | +-----------------+
While it works for this test data, it does have a flaw. If the same number appears 5 times in a row, it will output that number 3 times instead of once. Here's an alternative:
data want;
count=0;
do until (last.num);
set have;
by num notsorted;
count + 1;
end;
if count >= 3;
keep num count;
run;
Please once again, refer to how to post a question help. Post test data in the form of a datstep!
As such:
if lag2(num)=num and lag(num)=num then output;
May work, nothing to test it on as not going to type in test data.
Thanks, and I have just tested and appears to work for the given test data:
data have; input id num; cards; 1 1 2 1 3 1 4 2 5 1 6 2 7 2 ; run; data want (drop=id); set have; if lag2(num)=num and lag(num)=num then output; run;
While it works for this test data, it does have a flaw. If the same number appears 5 times in a row, it will output that number 3 times instead of once. Here's an alternative:
data want;
count=0;
do until (last.num);
set have;
by num notsorted;
count + 1;
end;
if count >= 3;
keep num count;
run;
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.