Friday, January 14, 2011

SAS Reshape: from Wide to Long and from Long to Wide compare


Reshape data from Wide to Long  (SAD)
/*************************  BEGIN FROM HERE  ******************************/
data wide;
  input famid faminc96 faminc97 faminc98 ;
cards;
1 40000 40500 41000
2 45000 45400 45800
3 75000 76000 77000
;
run;

data long;
  set wide;
  array afaminc(96:98) faminc96-faminc98;
  do year = 96 to 98;
     faminc=afaminc[year];
        output;  /*Output each observation*/
   end;
   keep famid year faminc;
run;
/**************************************************************************
 Each time SAS read 4 data. (famid faminc96 faminc97 faminc98)
 Use the array to read these 4 data into faminc vertically
 SAS reads next 4 data, and then do it again.
**************************************************************************/

proc print data=&syslast;
run;
***************************** END OF CODE  ********************************


Reshape data from Long to Wide  (SBRAII)
/*************************  BEGIN FROM HERE  *****************************/
DATA long ;
  INPUT famid year faminc ;
CARDS ;
1 96 40000
1 97 40500
1 98 41000
2 96 45000
2 97 45400
2 98 45800
3 96 75000
3 97 76000
3 98 77000
;
RUN ;

proc sort data=long;
  by famid;
run;

data wide;
  set long;
  by famid;
  retain faminc96-faminc98;
  array afaminc(96:98) faminc96-faminc98;
  if first.famid then
  do;
    do i =96 to 98;
      afaminc[i]=0;
     end;
   end;
   afaminc[year]=faminc;
   if last.famid then output;
   keep famid faminc96-faminc98;
run;
 
/*************************************************************************
 SAS read one faminc each time, and then store it in the array
 Read three faminc, then famid will change
**************************************************************************/

proc print data=&syslast;
run;
***************************** END OF CODE  *********************************

No comments:

Post a Comment