SAS行列转换一定要用proc transpose?No No No,介绍其他2种替代方案同样实现!
行列转换简单示例
Before转换
Obs |
TRTN |
AGEGR1N |
AVAL |
1 |
1 |
1 |
11 |
2 |
1 |
2 |
12 |
3 |
1 |
3 |
13 |
4 |
2 |
1 |
21 |
5 |
2 |
2 |
22 |
6 |
2 |
3 |
23 |
After转换
Obs |
TRTN |
AGEGR_1 |
AGEGR_2 |
AGEGR_3 |
1 |
1 |
11 |
12 |
13 |
2 |
2 |
21 |
22 |
23 |
>首选方案
proc transpose一发入魂?code示例如下
data test;
TRTN=1; AGEGR1N=1; AVAL=11; output;
TRTN=1; AGEGR1N=2; AVAL=12; output;
TRTN=1; AGEGR1N=3; AVAL=13; output;
TRTN=2; AGEGR1N=1; AVAL=21; output;
TRTN=2; AGEGR1N=2; AVAL=22; output;
TRTN=2; AGEGR1N=3; AVAL=23; output;
run;
proc transpose data=test out=test_tran0 prefix=AGEGR_;
by TRTN;
id AGEGR1N;
var AVAL;
run;
>替代方案1
利用data过程步的retain+if first/if last组合
data test_tran1;
set test;
by TRTN AGEGR1N;
retain AGEGR_1 AGEGR_2 AGEGR_3;
if first.TRTN then call missing(AGEGR_1,AGEGR_2,AGEGR_3);
if AGEGR1N=1 then AGEGR_1=AVAL;
if AGEGR1N=2 then AGEGR_2=AVAL;
if AGEGR1N=3 then AGEGR_3=AVAL;
if last.TRTN then output;
keep TRTN AGEGR_1 AGEGR_2 AGEGR_3;
run;
>替代方案2
讨厌data过程步,特别偏爱sql的小伙伴们可以看看下面示例code,估计很少有人用,我反正是没见过其他sp这个写过,嘿嘿
proc sql noprint;
create table test_tran2 as
select distinct TRTN
, max(case when AGEGR1N=1 then AVAL else . end) as AGEGR_1
, max(case when AGEGR1N=2 then AVAL else . end) as AGEGR_2
, max(case when AGEGR1N=3 then AVAL else . end) as AGEGR_3
from test
group by TRTN;
quit;
>两种方案的执行结果
结论
码code是个辛苦的体力活,偶尔换个解法,换个思维,枯燥也许会变的有趣,工作也许更有动力。
以上介绍仅供参考,具体问题具体对待,如果有更有趣的解法欢迎留言探讨,共同进步。