【问题标题】:Summing Multiple Columns By Date in SAS在SAS中按日期对多列求和
【发布时间】:2016-12-14 20:31:45
【问题描述】:

我在 SAS 中有这样的数据;

Date    Type_1  Type_2
4/8/2015 21654.72   .
4/9/2015 34490.13   .
4/9/2015 32429      .
4/9/2015    .      24438.76
4/9/2015    .      54043.18
4/9/2015    .      58969.06
4/9/2015    .      57721.01
4/9/2015    .      46313.08
4/10/2015   .      49974.06
4/10/2015   .      52403.41
4/10/2015 25260.07  .
4/10/2015 27891.98  .
4/11/2015   .      28130.06
4/11/2015 24886.15  .
4/11/2015 10407.6   .
4/11/2015 49422.71  .
4/11/2015 15242.28  .
4/11/2015   .      25295.52
4/11/2015   .      17522.67
4/13/2015 29798.99  .
4/13/2015 10445.17  .
4/13/2015 23678.87  .
4/13/2015   .      35470.87
4/13/2015   .      33941.01
4/13/2015   .      30206.06
4/13/2015   .      26591.98

我正在尝试使用 SAS 数据步骤汇总 type_1 和 type_2 并按日期合并两列。

我试过这样的代码:

data work.data;
    set data_consolidated;
    by date;

    if first.date then total_type_1=0 and total_type_2=0;
    total_type_1 + type_1;
    total_type_2 + type_2;
    if last.date then output;
    drop type_1;
    drop_type_2;
run;

此代码合并日期,但不是将日期列中的所有值相加,而是以累积方式将当前值添加到所有先前值。

为了清楚起见,下面是我试图让数据看起来像的示例:

date     type_1        type_2
4/8/2015    21654.72    .
4/9/2015    66919.13    128472.85
4/10/2015   53152.05    102377.47
4/11/2015   99958.74    70948.25

非常感谢任何建议或帮助。

【问题讨论】:

    标签: sas datastep consolidation


    【解决方案1】:

    试试这个:

    proc sql;
       select distinct date, sum(type_1) as type_1, sum(type_2) as type_2 from data_consolidated group by date;
    quit;
    

    【讨论】:

    • 这非常有效。我想我在数据步骤上已经下定决心,并没有研究 proc sql。谢谢@shenglin chen!
    【解决方案2】:

    我认为你的问题是这条线。

    if first.date then total_type_1=0 and total_type_2=0;
    

    这将导致根据赋值语句右侧布尔表达式的评估将 total_type_1 设置为 1(真)或 0(假)。 total_type_2 的值没有改变。

    也许你打算这样做:

    if first.date then total_type_1=0;
    if first.date then total_type_2=0;
    

    if first.date then do;
      total_type_1=0;
      total_type_2=0;
    end; 
    

    使用 DOW 循环是在数据步骤中执行此类操作的好方法。

    data want;
      do until(last.date);
        set data_consolidated;
        by date;
        total_type_1 = sum(total_type_1,type_1,0);
        total_type_2 = sum(total_type_2,type_2,0);
      end;
      drop type_1 type_2 ;
    run;
    

    【讨论】:

    • 这似乎是个问题。现在很明显,但我没有意识到需要将行分成两部分才能正确执行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    相关资源
    最近更新 更多