【问题标题】:Sum Variables Conditionally in SAS EG在 SAS EG 中有条件地对变量求和
【发布时间】:2017-03-02 07:52:40
【问题描述】:

我正在尝试在 SAS EG 中创建计算变量。

data data1;
    input ID Type Payment_Amt;
    cards;
    1 Voucher $50
    1 Cash $50
    1 Cash $20
    1 Card $20
    1 Card $50
;

需要的数据:

ID        TotalAmtVoucher        TotalAmtCash        TotalAmtCard
1                      50 美元                                                             70 美元

这可能吗? 如果我缺少任何需要的细节,请告诉我。 非常感谢!

【问题讨论】:

    标签: sas


    【解决方案1】:

    Payment_Amt 的输入数据将是前面带有 $ 的字符变量。使用起来真的很尴尬。我建议使用数字金额并使用dollar格式将它们显示为货币值。

    但是,如果您的数据已经是字符格式,您可以使用以下方法将它们转换为数字:

    data data1;
      set data1;
      Payment_Amt2 = input(substr(Payment_Amt,2),best.);
    
      format Payment_Amt2 dollar3.;
    
      drop Payment_Amt;
      rename Payment_Amt2 = Payment_Amt;
    

    运行;

    这仅使用substr()获取字符串中$之后的值,然后使用input()函数将它们转换为数值。

    要获得总数,您可以使用proc sql,然后转置数据:

    proc sql;
      create table want0 as
      select distinct id, type, sum(payment_amt) as total
      from data1
      group by type;
    quit;
    
    proc transpose data = want0 out = want(drop = _name_) prefix = TotalAmt;
      by id;
      id type;
    run;
    

    proc sql 步骤将通过 group by 语句对特定 type 的所有值求和。然后,您可以使用proc transpose 将数据转换为您想要的格式。使用prefix= 选项允许您在变量名中指定"TotalAmt" 前缀。

    【讨论】:

      【解决方案2】:

      如果类型的值是已知的、静态的且很少,您可以执行以下操作:

      data data1;
          input ID : 8. Type : $char10. Payment_Amt : dollar4.;
          cards;
      1 Voucher $50
      1 Cash $50
      1 Cash $20
      1 Card $20
      1 Card $50
      2 Voucher $90
      2 Cash $30
      ;
      run;
      
      proc sql;
          create table data_want as
          select ID,
                 sum(ifn(Type="Voucher",Payment_Amt,0))   as TotalAmtVoucher format=dollar4.,
                 sum(ifn(Type="Cash",Payment_Amt,0))      as TotalAmtCash    format=dollar4.,
                 sum(ifn(Type="Card",Payment_Amt,0))      as TotalAmtCard    format=dollar4.
          from data1
          group ID;
      quit;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        • 2022-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多