Help using Base SAS procedures

PROC FORMAT for ordinal

Accepted Solution Solved
Reply
New Contributor
Posts: 4
Accepted Solution

PROC FORMAT for ordinal

Hi all,

this may be a very simple question but I have not found an answer yet. Is there a format that can put cardinal numbers into ordinals? Turning, e.g., 1 to 1st, 2 to 2nd, etc?


Accepted Solutions
Solution
‎06-04-2014 11:20 AM
Super User
Posts: 19,789

Re: PROC FORMAT for ordinal

It's not that bad, this is borrowed from a 2006 post from David Cassell and

data ordinal_format;

    length label $8.;

  do number=1 to 300;

    numstring = put(number, 16. -l);

    if prxmatch('/(?<!1)1\s*$/',numstring) then ending='st';

    else if prxmatch('/(?<!1)2\s*$/',numstring) then ending='nd';

    else if prxmatch('/(?<!1)3\s*$/',numstring) then ending='rd';

    else ending = 'th';

    ordstring =catt(numstring, ending);

      start=number;

      label=ordstring;

      fmtname="ordinal_fmt";

      type="N";

      output;

  end;

    keep start label fmtname type;

run;

proc format cntlin=ordinal_format;

run;

data want;

do i =1 to 100;

    j=i;

    output;

end;

format j ordinal_fmt.;

run;

View solution in original post


All Replies
Super User
Posts: 19,789

Re: PROC FORMAT for ordinal

You can always make your own. Does your data have a specific range or is any number possible?

New Contributor
Posts: 4

Re: PROC FORMAT for ordinal

Thanks Reeza...I was hoping to avoid creating my own due to the large range and the fact that the range could grow over time, so a SAS delivered one was preferable.

Anyway, the range is currently 1 (1st) to 127 (127th), although most values of interest cap out at around 22.

Solution
‎06-04-2014 11:20 AM
Super User
Posts: 19,789

Re: PROC FORMAT for ordinal

It's not that bad, this is borrowed from a 2006 post from David Cassell and

data ordinal_format;

    length label $8.;

  do number=1 to 300;

    numstring = put(number, 16. -l);

    if prxmatch('/(?<!1)1\s*$/',numstring) then ending='st';

    else if prxmatch('/(?<!1)2\s*$/',numstring) then ending='nd';

    else if prxmatch('/(?<!1)3\s*$/',numstring) then ending='rd';

    else ending = 'th';

    ordstring =catt(numstring, ending);

      start=number;

      label=ordstring;

      fmtname="ordinal_fmt";

      type="N";

      output;

  end;

    keep start label fmtname type;

run;

proc format cntlin=ordinal_format;

run;

data want;

do i =1 to 100;

    j=i;

    output;

end;

format j ordinal_fmt.;

run;

New Contributor
Posts: 4

Re: PROC FORMAT for ordinal

Ha, I usually avoid prxmatch like the plague but here it is, good answer!

Super User
Posts: 19,789

Re: PROC FORMAT for ordinal

So do I, ergo the "borrowed code" :smileygrin:

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 629 views
  • 0 likes
  • 2 in conversation