您可以通过 PROC FREQ 手动定义列顺序吗?

ese*_*sel 2 sas bar-chart

我是 SAS 新手,但我正在准备一个解释一些基本 SAS 的讲座。我想展示如何使用 SAS(版本 9.4)创建条形图。为此,我使用 SAS 中的“heart”示例数据集。

如果我通过变量“Smoking_Status”创建条形图PROC FREQ,我会得到无用的条形排序。

proc freq data=sashelp.heart;
  tables Smoking_Status / plots = freqplot;
run;
Run Code Online (Sandbox Code Playgroud)

通过 FREQ 绘制条形图

PROC FREQ是否可以通过参数手动订购条形ORDER=?我不明白怎么办。我希望图表有很好的描述,而不是在标签前加上“1-”或“2-”前缀,以便能够按字母顺序对它们进行排序,因为这会降低结果图的可读性。

我可以通过 达到想要的结果SGPLOT

proc sgplot data=sashelp.heart;
  vbar Smoking_Status;  
  title "Distribution of smoking_status from sashelp.heart dataset";
  xaxis display=(nolabel) values=('Non-smoker' 'Light (1-5)' 'Moderate (6-15)' 
    'Heavy (16-25)' 'Very Heavy (> 25)');
run;
Run Code Online (Sandbox Code Playgroud)

通过 SGPLOT 绘制条形图

我的问题是:是否还有一种方法可以通过 实现此结果PROC FREQ?我想确定是否是这种情况,因为我想展示这个问题最简单、最直接的解决方案。

PBu*_*lls 5

是的,您可以通过ORDER=声明来做到这一点。默认值为INTERNAL,它适用于未格式化的值并按字母顺序放置字符变量。将分组变量转换为数字并应用设置所需标签的格式通常会更灵活。或者,您可以ORDER=DATA在数据集顶部以正确的顺序使用和添加记录,例如权重为零。

两种方法的 SAS 代码示例(您只需执行一种):

/* Formats for option 1, can also generate these from the data. */
proc format;
   invalue smoke_num
      "Non-smoker" = 1
      "Light (1-5)" = 2
      "Moderate (6-15)" = 3
      "Heavy (16-25)" = 4
      "Very Heavy (> 25)" = 5;

   value smoke_label
      1 = "Non-smoker"
      2 = "Light (1-5)"
      3 = "Moderate (6-15)"
      4 = "Heavy (16-25)"
      5 = "Very Heavy (> 25)";
run;



data want;
   /* Option 2: add dummy records with zero weight for ORDER=DATA. */
   length Smoking_Status $17;
   if _N_ eq 1 then do;
      wt = 0;
      do smoking_status = "Non-smoker",
                          "Light (1-5)",
                          "Moderate (6-15)",
                          "Heavy (16-25)",
                          "Very Heavy (> 25)";
         output;
      end;
   end;
   wt = 1;

   set sashelp.heart;
   /* Option 1: set order through formatted numeric variable. */
   smokeN = input(smoking_status, smoke_num.);
   format smokeN smoke_label.;

   output; /* Needed for option 2 (implicit output is gone). */
run;

/* Option 1. */
proc freq data=want order=internal;
   tables smoken / plots=freqplot;
   format smoken smoke_label.; /* Already applied above as well. */
   weight wt; /* Only needed to exclude dummy records if they are present. */
run;


/* Option 2. */
proc freq data=want order=data;
   tables smoking_status / plots=freqplot;
   weight wt;
run;
Run Code Online (Sandbox Code Playgroud)