【问题标题】:Using the sum of the columns, to create a new varible使用列的总和,创建一个新变量
【发布时间】:2017-05-09 04:20:40
【问题描述】:

我有数据集,其中包含州、玉米和棉花。我想在 SAS 中创建一个新变量 Corn_Pct(州玉米产量相对于该国玉米产量的百分比)。 Cotton_pct 也一样。 数据样本:(数字不是真实的)

    State Corn Cotton
    TX    135  500
    AK    120  350
    ...

有人可以帮忙吗?

【问题讨论】:

  • 您希望发布的样本数据有什么输出?你尝试了什么?结果与您想要的结果有何不同?
  • 我应该得到两个新列。起初我尝试了 [Corn_pct = (corn /sum(of corn))*100;],但这只是给了我 100。我没有意识到 [sum] 中只有一个变量,我将只是找回那个号码。我知道有办法做到这一点,但我不记得了。

标签: sas enterprise-guide


【解决方案1】:

您可以使用简单的Proc SQL 来完成此操作。让数据集为“测试”,

Proc sql ;
create table test_percent as 
select *,
Corn/sum(corn) as Corn_Pct format=percent7.1,
Cotton/sum(Cotton) as Cotton_Pct format=percent7.1
from test
;
quit;

如果您有很多列,您可以使用Arraysdo loops 每次自动生成百分比。

【讨论】:

    【解决方案2】:

    我计算了Inner Query 中一列的总数,然后使用该总数在外部查询中使用Cross Join 进行计算

    嘿试试这个:-

     /*My Dataset */
        Data Test;
        input     State $  Corn  Cotton ;
        cards;
        TK 135 500
        AK 120 350
        CK 100 250
        FG 200 300
        run;
    
        /*Code*/
    
        Proc sql;
        create table test_percent as 
        Select a.*, (corn * 100/sm_corn) as Corn_pct, (Cotton * 100/sm_cotton) as Cotton_pct
        from test a
        cross join
        (
        select sum(corn) as sm_corn ,
        sum(Cotton) as sm_cotton
        from test
        ) b ;
        quit;
    
            /*My Output*/
     State Corn Cotton    Corn_pct     Cotton_pct
         TK 135  500      24.32432432   35.71428571
         AK 120  350      21.62162162   25
         CK 100  250      18.01801802   17.85714286
         FG 200  300      36.03603604   21.42857143
    

    【讨论】:

      【解决方案3】:

      在这里,您可以使用proc meansdata step

      proc means data=test sum noprint;
          output out=test2(keep=corn cotton) sum=corn cotton;
      quit;
      
      data test_percent (drop=corn_sum cotton_sum);
          set test2(rename=(corn=corn_sum cotton=cotton_sum) in=in1) test(in=in2);
          if (in1=1) then do;
              call symput('corn_sum',corn_sum);
              call symput('cotton_sum',cotton_sum);
          end;
          else do;
              Corn_pct = corn/symget('corn_sum');
              Cotton_pct = cotton/symget('cotton_sum');
          output;
          end;
      run;
      

      【讨论】:

        猜你喜欢
        • 2022-12-06
        • 1970-01-01
        • 1970-01-01
        • 2018-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多