SAS跨行添加

时间:2016-02-17 18:51:36

标签: sas

附件是数据集的示例,其中ID#列具有一些相同的值,但Dollar Amount列具有相同ID#的不同值。如何在ID#相同的行之间添加Dollar Amount,并基本上为该ID#创建摘要行?该列表比这长得多,因此指定每个ID#不是一个选项。

enter image description here

3 个答案:

答案 0 :(得分:1)

也有SQL选项,但这就​​是在数据步骤中进行总计/求和的方法。

data have;
input id $1. dollar_amount 8.;
format dollar_amount dollar25.;
cards;
1   24
2   53
2   67
3   35
4   86
5   245
6   353
6   56
7   21
;
run;

proc sort data=have noequals; /*Only run if not already sorted*/
by id;
run;

data want(drop=dollar_amount);
set have;
by id;
if first.id then dollar_total = .;
format dollar_total dollar25.;
dollar_total + dollar_amount;
if last.id then output;
run;

答案 1 :(得分:0)

如果您不想使用PROC SQL并想要输入数据中的实际摘要行(我认为这就是您所要求的),这里是使用标志来标识总和行的简单数据步骤:

data have;
input id $1. dollar_amount 8.;
format dollar_amount dollar25.;
cards;
1   24
2   53
2   67
3   35
4   86
5   245
6   353
6   56
7   21
;
run;

proc means data = have noprint;
    by id;
    var dollar_amount;
    output out=sum_data (drop=_type_ _freq_) sum=dollar_amount ;
run;

data sum_data; set sum_data;
    sum_row=1;
run;

data final;
    set have sum_data;
run;

proc sort data = final;
    by id sum_row;
run;

如果您只想要一个按唯一ID生成总和的输出数据集,那么只需使用:

proc means data = have noprint;
    by id;
    var dollar_amount;
    output out = want (drop=_type_ _freq_) sum=dollar_amount_sum;
run;

答案 2 :(得分:0)

和PROC SQL等价......

data have;
input id $1. dollar_amount 8.;
format dollar_amount dollar25.;
cards;
1   24
2   53
2   67
3   35
4   86
5   245
6   353
6   56
7   21
;
run;


proc Sql;
create table want as
  Select 
ID,
sum(dollar_amount) as dollar_amount format dollar25.

  from have
group by ID
  ;
quit;

enter image description here