【问题标题】:Convert column to row matrix with the frequency of its values in SAS SQL使用 SAS SQL 中值的频率将列转换为行矩阵
【发布时间】:2021-08-10 14:17:34
【问题描述】:

我有一个看起来像这样的表(使用 SAS SQL):

id color
1 red
2 blue
1 green
1 red
2 red
2 blue

我正试图让它看起来像这样:

id red blue green
1 2 0 1
2 1 2 0

总而言之,我试图将列转置为行,然后在单元格中具有每个类别出现每个 ID 的频率。

提前谢谢你!

【问题讨论】:

    标签: sql matrix transpose


    【解决方案1】:

    第一次计数。然后转置。

    proc freq data=have ;
      tables id*color / noprint out=counts;
    run;
    proc transpose data=counts out=want(drop=_name_ _label_);
      by id;
      id color;
      var count;
    run;
    

    如果将 SPARSE 选项添加到表语句中,则可以得到零而不是丢失。

    tables id*color / noprint sparse out=counts;
    

    【讨论】:

      【解决方案2】:

      使用proc sql,可以使用条件聚合:

      proc sql;
          select id,
                 sum(case when color = 'red' then 1 else 0 end) as red,
                 sum(case when color = 'blue' then 1 else 0 end) as blue,
                 sum(case when color = 'green' then 1 else 0 end) as green
          from t
          group by id;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 1970-01-01
        • 2014-04-11
        • 2018-11-17
        • 1970-01-01
        • 2016-11-13
        相关资源
        最近更新 更多