BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Geo-
Quartz | Level 8

 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

;

IdNum
11
21
31
42
51
62
72
  


+-----------------+For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.

| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

 

1 ACCEPTED SOLUTION

Accepted Solutions
Astounding
PROC Star

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;

View solution in original post

4 REPLIES 4
RW9
Diamond | Level 26 RW9
Diamond | Level 26

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.

Geo-
Quartz | Level 8
Sir,have updated as what you mentioned.
RW9
Diamond | Level 26 RW9
Diamond | Level 26

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;
Astounding
PROC Star

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;

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 5019 views
  • 1 like
  • 3 in conversation