Creating a SAS Format from a Data Set

SAS Formats are useful to the SAS programmer. They are usually used to map one value into another. We can create a format from a data set.  The most common way to create a format is use PROC FORMAT.  The picture below is an example of a data set with two columns, analysis visit and analysis visit number.

Format

This post will illustrate four different methods to create a format called $visit from this data set.

  1. CALL EXECUTE
    data _null_;
        set demo end=eof;
        if _n_=1 then call execute('proc format; value visit');
        call execute(cats(AVISITN)||' = '||quote(cats(AVISIT)));
        if eof then call execute('; run;');
    run;
    
  2. Macro variable
    proc sql noprint;
        select catx(' = ', cats(AVISITN), quote(cats(AVISIT))) into :fmtlst separated by ' '
            from demo
            order by AVISITN;
    quit;
    
    proc format;
        value visit
        &fmtlst;
    run;
    
  3. CNTLIN= option
    proc sql;
        create table fmt as
            select distinct 'visit' as FMTNAME
                 , AVISITN as START
                 , cats(AVISIT) as label
            from demo
            order by AVISITN
            ;
    quit;
    
    proc format library=work cntlin=fmt;
    run;
    
  4. FILENAME
    proc sql;
        create table fmt as
            select distinct AVISITN
                 , quote(cats(AVISIT)) as AVISIT
            from demo
            order by AVISITN
            ;
    quit;
    
    /*Write the generated code to a temporary file*/
    filename code temp;
    data _null_;
        file code;
        set fmt;
        if _n_=1 then put +4 'value visit';
        put +14 AVISITN ' = ' AVISIT;
    run;
    
    proc format;
        %inc code / source2;
        ;
    run;
    
Xianhua Zeng /
Published under (CC) BY-NC-SA in categories Code  tagged with CALL EXECUTE  FILENAME  PROC FORMAT 

Previous Splitting a String Using Perl Regular Expression
Next Parsing Comments from aCRF with Perl Regular Expression