BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
chetan3125
Obsidian | Level 7

Hi, 
I have data as below and want to flag youngest 3 and oldest 3 records as shown in the screenshot below. 

Is there any efficient way to do this ?

Thanks. 

data have;
length name $8 sex $1;
input name  sex    age  ;
cards ;
Joyce F 5
Thomas M 6
James M 12
Jane F 3
John M 12
Louise F 4
Robert M 12
Alice F 11
Barbara F 6
Jeffrey M 8
Alfred M 1
Carol F 16
Henry M 11
Judy F 8
Janet F 7
Mary F 12
Ronald M 13
William M 5
Philip M 8
;
run;

proc sort data=have ; by age ; run;

Want as below-- 

 

WANTWANT

1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User
data have;
length name $8 sex $1;
input name  sex    age  ;
cards ;
Joyce F 5
Thomas M 6
James M 12
Jane F 3
John M 12
Louise F 4
Robert M 12
Alice F 11
Barbara F 6
Jeffrey M 8
Alfred M 1
Carol F 16
Henry M 11
Judy F 8
Janet F 7
Mary F 12
Ronald M 13
William M 5
Philip M 8
;
run;

proc sort data=have ; by age ; run;
data temp;
 set have end=last;
 by age;
 n+first.age;
 if last then call symputx('n',n);
run;
data want;
 set temp;
 if n in (1 2 3) then youngest3=1;
 if n in (%eval(&n-2) %eval(&n-1) &n) then oldest3=1;
run;

View solution in original post

3 REPLIES 3
Ksharp
Super User
data have;
length name $8 sex $1;
input name  sex    age  ;
cards ;
Joyce F 5
Thomas M 6
James M 12
Jane F 3
John M 12
Louise F 4
Robert M 12
Alice F 11
Barbara F 6
Jeffrey M 8
Alfred M 1
Carol F 16
Henry M 11
Judy F 8
Janet F 7
Mary F 12
Ronald M 13
William M 5
Philip M 8
;
run;

proc sort data=have ; by age ; run;
data temp;
 set have end=last;
 by age;
 n+first.age;
 if last then call symputx('n',n);
run;
data want;
 set temp;
 if n in (1 2 3) then youngest3=1;
 if n in (%eval(&n-2) %eval(&n-1) &n) then oldest3=1;
run;
PaigeMiller
Diamond | Level 26
PROC RANK gives the user control over how ties are handled, which seems important in this example. PROC Sort does not give the user control over ties.
--
Paige Miller

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
  • 3 replies
  • 1264 views
  • 1 like
  • 4 in conversation