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 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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
  • 712 views
  • 1 like
  • 4 in conversation