首页 > 解决方案 > SAS:proc hpbin 函数

问题描述

我拥有的数据是

Year Score
2020  100
2020  45 
2020  82
.
.
.
2020  91
2020  14
2020  35

我想要的输出是

Score_Ranking Count_Percent Cumulative_count_percent Sum
top100        x             y                        z 
101-200
.
.
.
800-900
900-989

该数据集同一年共有 989 个观测值。我想将整个数据集分成 10 个 bin,但将大小设置为 100。但是,如果我使用 proc hpbin 函数,我的结果会被分成 989/10 个 bin。有没有办法确定垃圾箱的大小?

另外,我想要显示比例、累积比例和分数总和的其他行。我怎样才能在垃圾箱旁边打印这些?

先感谢您。

标签: sassizeprocbin

解决方案


  1. 对数据进行排序
  2. 分类到垃圾箱
  3. 将 PROC FREQ 用于#/累积计数
  4. 通过使用 WEIGHT 将 PROC FREQ 用于 SUM
  5. 合并结果

或在同一数据步骤中执行 3-4。

我实际上不确定前两列会告诉你什么,因为除了最后一列之外,它们都是相同的。

首先生成一些可以使用的假数据,排序很重要!

*generate fake data;
data have;
do score=1 to 998;
output;
end;
run;

proc sort data=have;
by score;
run;

方法#1

请注意,我在这里使用了一个视图,而不是一个数据集,如果效率可能是一个问题,它可以提供帮助。

*create bins;
data binned / view=binned;
set have ;
if mod(_n_, 100) = 1 then bin+1;    
run;

*calculate counts/percentages;
proc freq data=binned noprint;
table bin / out=binned_counts outcum;
run;

*calculate sums - not addition of WEIGHT;
proc freq data=binned noprint;
table bin / out=binned_sum outcum;
weight score;
run;

*merge results together;
data want_merged;
merge binned_counts binned_sum (keep = bin count rename = count= sum);
by bin;
run;

方法#2

还有另一种方法,它需要数据的单次传递,而不是像 PROC FREQ 方法中的多次传递:

*manual approach;
data want;
set have 
    nobs = _nobs /*Total number of observations in data set*/ 
    End=last /*flag for last record*/;
    
*holds values across rows and sets initial value;   
retain bin 1 count cum_count cum_sum 0 percent cum_percent ;

*increments bins and resets count at start of each 100;
if mod(_n_, 100) = 1 and _n_ ne 1 then do;
    *output only when end of bin;
    output;
    bin+1;
    count=0;    
end;

*increment counters and calculate percents;
count+1;
percent = count / _nobs;
cum_count + 1;
cum_percent = cum_count / _nobs;
cum_sum + score;

*output last record/final stats;
if last then output;

*format percents;
format percent cum_percent percent12.1;

run;


推荐阅读