Help using Base SAS procedures

Proc Format

Reply
Regular Contributor
Posts: 157

Proc Format

Hi,

I am using a format for some counties

PROC FORMAT;

  VALUE  $ CNTYSTAT

  '01' - '99' = 'KNOWN '

  OTHER = 'UNKNOWN'

  ;

  RUN;

The problem i am having is

if the county has code like 01A then also it is printing as known.

If the county code is like 01A then it should print it as unknown.

Super User
Posts: 5,499

Re: Proc Format

Jason,

If that's what you want to get, then the problem is that you created a character format.  As character strings, both of these comparisons are true:

'01' < '01A'

'01A' < '99'

So 01A is in range, and prints as KNOWN.  Even a character string like '255' would fall within the KNOWN range.

Fixing the problem is another story.  First, create a numeric format instead of a character format.  If it's a matter of selecting observations, then select with:

if put( input(county_code, ??3.), cntystat.) = 'KNOWN';

But if it's just a matter of printing, you will need to create a numeric version of COUNTY_CODE, such as:

county_code_num = input(county_code, ??3.);

The ?? will suppress messages about invalid numeric data when you process values such as 01A.

Good luck.

Respected Advisor
Posts: 3,156

Re: Proc Format

Jason,

Basically like Astounding said, there is no clean-cut solution. You will have to either create another variable like option1 or lay out all of the possibilities using Macro like option2:

/*Option1*/

data have;

input a$;

b=ifc(lengthn(a)<=2, compress(a,,'kd'), 'ZZZ');

format b $cntystat10.;

cards;

01

0A

02

100

10A

;

run;

proc print;run;

/*Option2*/

%macro test;

PROC FORMAT;

  value $ CNTYSTAT

  %let zi=01;

  %do i=2 %to 99;

  %let zi=&zi,%sysfunc(putn(&i,z2.));

%end; &zi = 'KNOWN'

  OTHER = 'UNKNOWN'

  ;

  RUN;

%mend;

%test

Haikuo

Super User
Posts: 10,023

Re: Proc Format

Another way is to make a format on your own .

data have;
input a $;
cards;
01
0A
02
100
10A
;
run;


data fmt;
retain fmtname 'cntystat'  type 'C' ;
 do i=1 to 99;
  start=put(i,z2.); label='KNOW  ';
  output;
 end;
 hlo='o';start=' ';label='UNKNOW';output;
 drop i;
run;
  
proc format cntlin=fmt;
run;

data want;
 set have;
 format a $cntystat8. ;
run;


Ksharp

PROC Star
Posts: 1,759

Re: Proc Format

You can do pretty much anything now with formats since you can use functions in 9.3.

Example:

proc fcmp outlib=sasuser.test.func32;

  function knownzip(ZIP $) $;

    return(trim(ifc('01'<=ZIP<='99' and length(ZIP)=2, 'KWOWN', 'UNKNOWN')));

  endsub;

run;

options cmplib=sasuser.test;

proc format ;

  value $ knownzip other=[knownzip()];

run;

data _null_;

  A='01 '; put A $knownzip.;

  A='01A'; put A $knownzip.;

run;

KWOWN

UNKNOWN

NOTE: DATA statement used (Total process time):

      real time           0.00 seconds

      cpu time            0.00 seconds

Ask a Question
Discussion stats
  • 4 replies
  • 258 views
  • 1 like
  • 5 in conversation