如何通过汇总另一个变量来对SAS中的变量进行排名

时间:2019-05-27 08:52:31

标签: sas rank

例如:

Groupvar    Value
A           5
A           1
B           0
B           9
B           8 
C           2
C           2

我想对Groupvar进行汇总,以汇总Value。因此,在此示例中,sum(A)= 6,sum(B)= 17,sum(C)=4。因此,等级1 = B,等级2 = A,等级3 = 6。

理想的输出:

Groupvar    Value    Rank
A           5         2
A           1         2
B           0         1
B           9         1
B           8         1
C           2         3
C           2         3

有什么想法可以做到吗?我可以创建一个proc摘要>然后等级>然后合并等级。但是我想知道是否还有更好的方法。

2 个答案:

答案 0 :(得分:1)

您也许可以使用LEVELS选项加上ORDER = FREQ创建的变量。例如。

data have;
   input Groupvar:$1. Value;
   cards;
A           5
A           1
B           0
B           9
B           8 
C           2
C           2
;;;;
   run;
proc summary nway order=freq missing;
   class groupvar;
   freq value;
   output out=test(drop=_type_ index=(groupvar)) / levels;
   run;
proc print;
   run;
data want;
   merge have test;
   by groupvar;
   run;
proc print; 
   run;

enter image description here

答案 1 :(得分:0)

您可以一次proc sql进行操作:

data test1;
    Ord + 1;
    input Groupvar$ Value;
    cards;
    A 5
    A 1
    B 0
    B 9
    B 8
    C 2
    C 2
    ;
run;

proc sql noprint;
    create table Test2 as 
    select Groupvar, sum(Value) as Sum
    from Test1
    group by Groupvar
    order by Sum
    ;

    create table Test3 as 
    select a.*, b.Sum, b.Rank
    from Test1 as a
    left join (
        select a.*, monotonic() as Rank
        from Test2 as a
    ) as b
    on a.Groupvar = b.Groupvar
    order by Ord
    ;
quit;