【发布时间】: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 的频率。
提前谢谢你!
【问题讨论】:
我有一个看起来像这样的表(使用 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 的频率。
提前谢谢你!
【问题讨论】:
第一次计数。然后转置。
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;
【讨论】:
使用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;
【讨论】: