Format the summarised variables from proc summary

2019-09-15 02:21发布

问题:

I'm using a Proc Summary, as I want to utilise a multilabel format. I've been going round and round trying to apply a format to my summarised outputs, but can't see how to get this without incurring warnings.

Proc Summary Data = Source CompleteTypes Missing NoPrint NWay;
 Class Brand / MLF;

 Var Id Total;

 Output Out = Results
        N(ID)      = Volume
        Sum(Total) = Grand_Total;
Run;

I want to format my Volume as Comma23. and the Grand_Total as Comma23.2. If I put a format statement after the outputs it warns me that the variables don't exist, but the dataset does have the format applied.

I would have thought that formatting a summarised variable would be a common action, but I can't find a way to apply it without getting the warnings. Is there something I'm missing?

Many thanks

回答1:

Some statistics like SUM inherit the format of the analysis variable. N statistics does not inherit the format but you can format the new variable if you can use the : trick shown in the example, and no warning is produced.

proc summary data=sashelp.class;
   class sex;
   output out=test n(age)=Nage sum(weight)=sum_weight;
   format nage: comma12. weight comma12.3;
   run;
proc contents varnum;
   run;
proc print;
   run;



回答2:

Another approach is to use proc template to apply the format. The format will be carried over into the newly created data set using the ods output. Use ods trace on to find (1) the name of the template to alter (2) the name of the object to output into a data set. In your case, you want to alter the Base.Summary template and output the Summary object. Both will be found in the log when you run ods trace in front of a proc step. This can be done with other procedures as well. For instance, a proc frequency of a single table has the template Base.Freq.OneWayList

/* Create Test Data */
data test (drop = num);
do num = 1 to 100;
    x = ceil(rand('NORMAL', 100, 10));
    output;
end;
run;

/* Check log with ODS Trace On to find template to alter and object to output */
ods trace on;
proc summary data = test sum n mean print;
var x;
run;
ods trace off;

/* Alter the Base.Summary template */
ods path reset;
ods path (PREPEND) WORK.TEMPLATE(UPDATE);

proc template;
edit Base.Summary;
    edit N;
        label = 'Count';
        header = varlabel;  
        format = Comma10.;
    end;
    edit Mean;
        label = 'Average';
        header = varlabel;  
        format = Comma10.;
    end;
    edit Sum;
        label = "Sum";
        header = varlabel;
        format = Comma10.;
    end;
end;
run;

/* Output Results (formatted) from the Proc */
ods output summary = results;
proc summary data = test sum n mean print stackodsoutput;
var x;
run;


回答3:

Use proc datasets to apply the format to your output dataset after proc summary has created it:

proc datasets lib = work;
  modify results;
  format Volume comma23. Grand_total comma23.2;
  run;
quit;