BookmarkSubscribeRSS Feed
Ronein
Onyx | Level 15

Hello

What is the way to sort the following char values in order to put them in the following order:

less 2K
2K-6K
6K-10K
10K-16K
16K-21K
21K-27K
27K-35.5K
more 35.5K
All Other

 

 

Data have;
input Category $30.;
cards;
10K-16K
16K-21K
21K-27K
27K-35.5K
2K-6K
6K-10K
All Other
less 2K
more 35.5K
;
Run;
4 REPLIES 4
japelin
Rhodochrosite | Level 12

how about this code?

data next;
  set have;
  catc=scan(category,1);
  if upcase(catc)='ALL' then catn=99;
  else if upcase(catc)='LESS' then catn=1;
  else if upcase(catc)='MORE' then catn=90;
  else catn=input(scan(category,1,'-','A'),best.);
  drop catc;
run;
proc sort data=next out=want(drop=catn);
  by catn;
run;

 

Kurt_Bremser
Super User

How do you assign the category in the first place?

If you want such categories ordered in a particular way, use a raw numeric value that determines the order, and assign a format that displays the string for it.

The format code might look like

proc format;
value mycat
  0 = "less 2K"
  1 = "2K-6K"
  2 = "6K-10K"
  3 = "10K-16K"
  4 = "16K-21K"
  5 = "21K-27K"
  6 = "27K-35.5K"
  7 = "more 35.5K"
  99 = "All Other"
;
run;
yabwon
Amethyst | Level 16

Hi, 

 

how about that:

Data have;
input Category $30.;
cards;
10K-16K
16K-21K
21K-27K
27K-35.5K
2K-6K
6K-10K
All Other
less 2K
more 35.5K
;
Run;

data want;
  set have;
  cat = compress(Category,"-.","kd");
  if cat = "" then cat = '9999';
run;

proc sort data = want sortseq=LINGUISTIC(numeric_colation=on);
  by cat;
run;
proc print;
run;

Bart

_______________
Polish SAS Users Group: www.polsug.com and communities.sas.com/polsug

"SAS Packages: the way to share" at SGF2020 Proceedings (the latest version), GitHub Repository, and YouTube Video.
Hands-on-Workshop: "Share your code with SAS Packages"
"My First SAS Package: A How-To" at SGF2021 Proceedings

SAS Ballot Ideas: one: SPF in SAS, two, and three
SAS Documentation



PaigeMiller
Diamond | Level 26

@Ronein wrote:

Hello

What is the way to sort the following char values in order to put them in the following order:

less 2K
2K-6K
6K-10K
10K-16K
16K-21K
21K-27K
27K-35.5K
more 35.5K
All Other


You have been asking this (or very similar) questions for probably 2 years now.

 

Leave numeric variables as numeric. Then they will sort as numeric. Use custom formats to make them appear 10k-16k, and so on.

--
Paige Miller

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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
  • 1042 views
  • 5 likes
  • 5 in conversation