* 데이터 전치를 위한 몇가지 방법을 나열해 보았습니다.
프로그램에 정답은 없다는 사실을 보여주는 예제입니다. 다양한 방법으로 유연하게 프로그램을 구현해보시기를 바랍니다.
data back;
input x1 $ x2 $;
id = ceil(_n_/4);
cards;
c1 123
c2 456
c3 789
c4 012
c1 111
c2 222
c3 333
c4 444
c1 222
c2 233
;
* 방법1 : 배열이용하기;
* 한번의 로직으로 처리가능;
data back1;
array var{*} $ c1-c4;
do i=1 to 4;
set back end=eof;
var{i}=x2;
if i=4 or eof then output;
end;
keep c:;
run;
* 방법2 : Retain으로 처리하는 방법;
* 그룹변수(ID)를 강제로 생성하여 처리;
data back2;
set back end=chk;
retain c1-c4 ' ';
by id;
if first.id then do;
c1 = '';
c2 = '';
c3 = '';
c4 = '';
end;
if x1='c1' then c1=x2;
else if x1='c2' then c2=x2;
else if x1='c3' then c3=x2;
else if x1='c4' then c4=x2;
if x1='c4' or chk then output;
run;
* 방법3 : Proc summary에서 IDGROUP 문장을 사용하여서 데이터 전치;
* 단점 : 여러단계의 조작 필요. 다시 Transpose로 전치 작업 필요;
* IDGROUP : 보통 ID변수별 최소/최대값 반환.;
proc sql ;
select max(N) into :outN
from (select count(*) as N
from back
group by x1) ;
quit;
run;
proc summary data=back nway missing;
class x1;
output out=back3 idgroup(obs out[&outN](x2)=)/ways levels inherit autoname;
run;
proc transpose data=back3 out=back31;
id x1;
var x2:;
run;
proc print;
run;
* 방법4 : Proc summary에서 IDGROUP 문장을 사용하여서 데이터 전치;
* 단점 : 그룹변수(ID)를 강제로 생성하여 처리;
proc sql;
select count(*) into :outN
from (select count(*) into :outN
from back
group by x1) ;
quit;
run;
proc summary data=back nway missing;
class id;
output out=back4 idgroup(obs out[&outN](x2)=);
run;
proc print;
run;
* 방법5 : PROC SQL이용하기. 만약 x2가 숫자이면;
data back;
input x1 $ x2;
cards;
c1 123
c2 456
c3 789
c4 012
c1 111
c2 222
c3 333
c4 444
c1 222
c2 233
;
proc sql;
select ceil(monotonic()/4),
sum(case when x1='c1' then x2 else 0 end) as c1,
sum(case when x1='c2' then x2 else 0 end) as c2,
sum(case when x1='c3' then x2 else 0 end) as c3,
sum(case when x1='c4' then x2 else 0 end) as c4
from back
group by 1;
quit;
Save $250 on SAS Innovate and get a free advance copy of the new SAS For Dummies book! Use the code "SASforDummies" to register. Don't miss out, May 6-9, in Orlando, Florida.