计算变量并添加新列

时间:2017-03-21 16:04:28

标签: sas

我想按类和num计算变量:

 id  class num   
  3   FE     351
  3   FE     351
  3   FE     352

如何创建新变量,如下表

  id   class    num    count
  3     FE       351    2
  3     FE       351    2
  3     FE       352    1   

2 个答案:

答案 0 :(得分:0)

假设基于该问题,ID不属于该组。如果不是这种情况,请适当添加。

首先创建一个计数表。

proc sql noprint;
create table counts as
   select class,
          num,
          count(*) as count
   from have
   group by class, num;
quit;

然后重新加入主表

proc sql noprint;
create table want as
select a.id,
       a.class,
       a.num,
       b.count
   from have as a
     left join
        counts as b
     on a.class = b.class 
      and 
        a.num = b.num;
quit;

答案 1 :(得分:0)

您可以在一个简单的SQL语句中执行此操作:

proc sql noprint;
    create table want as
    select id, class, num, count(num) as count
    from have
    group by num;
quit;