在 SAS 中使用 PROC SQL 将 table 从长转置为宽

Using PROC SQL in SAS to transpose a table from long to wide

我正在审查 Life Imitates Art:ODS 输出数据集,看起来像在 http://www.mwsug.org/proceedings/2013/BB/MWSUG-2013-BB12.pdf 列出的输出,其中作者强制从 PROC 输出的数据集类似于它们的表格描述输出。作者的代码是:

proc print data=sashelp.bweight(obs=5); run;

Proc Tabulate MISSING
Data=sashelp.bweight
Out=outequals(drop=_:);
Class ed smoke;
Tables ed, smoke /
 box="(Table in ODS Destination)";
Run;

Proc Print
Data=outequals noobs;
Run;

Proc Transpose
Data=outequals
 Out=twowaytable(drop=_:)
 prefix=smoke;
 By ed;
 ID smoke;
Var N;
Run; 

我想知道是否有一种使用 proc sql 来执行此操作的好方法,因为在过去,随着问题变得越来越复杂,proc 转置似乎不灵活。我想出了一个解决方案(如下),但我不禁想知道是否可以更有效地使用 PROC SQL。

proc sql ; 
create table col2_a as 
select * from outequals where smoke eq 1 and ed = 0 
outer union 
select * from outequals where smoke eq 1 and ed = 1 
outer union 
select * from outequals where smoke eq 1 and ed = 2 
outer union
select * from outequals where smoke eq 1 and ed = 3
;
quit;

proc sql ; 
create table col2_b as 
select monotonic() as key, * 
from col2_a 
; quit;

proc print data=col1_b ; run;

proc sql ; 
create table report as 
select 
a.ed as ed,
a.N as Smokers_HC,
b.n as NonSmokers_HC
from 
col1_b a join col2_b b 
on a.key eq b.key
;quit;

我更喜欢转置解决方案,因为它是动态的,Proc SQL 需要对答案进行硬编码。

这里是 'a' Proc SQL 解决方案:

proc sql;
create table want as
select ed, sum(smoke=1) as smoke1, sum(smoke=0) as smoke0
from sashelp.bweight
group by ed
order by ed;
quit;