Download long.csv
(see “CSV format” under “Files used in the examples”)
*To import the data;
proc import datafile = 'C:/long.csv' out = long dbms = csv replace;
getnames = yes;
run;
Option 1: Reshape using proc transpose
Option 2: Reshape using SAS arrays
Option 3: Reshape using macro %towide
Option 4: Reshape using proc summary
* Datasets MUST be sorted on ID variable prior to reshaping; proc sort data=long; by first last age; run; proc transpose data=long out=wide (drop=_name_); by first last age; id type group; var plant; run; proc print data=wide; title 'wide'; run; |
* Datasets MUST be sorted on ID variable prior to reshaping; proc sort data=long; by first last age; run; data wide; set long; by first last age; key=catt(type,group); if key='VeggieA' then key=1; else if key='FruitA' then key=2; else if key='VeggieB' then key=3; else if key='FruitB' then key=4; else if key='VeggieC' then key=5; else key=6; keep first last age VeggieA FruitA VeggieB FruitB VeggieC FruitC; retain VeggieA FruitA VeggieB FruitB VeggieC FruitC; array aplant(1:6) $ VeggieA FruitA VeggieB FruitB VeggieC FruitC; if first.age then do; do i=1 to 6; aplant(i)=''; end; end; aplant(key)=plant; if last.age then output; run; proc print data=wide; title 'wide'; run; |
* recode the character time-varying variable to numeric variable; data long_recode; set long; key=catt(type,group); if key='VeggieA' then key=1; else if key='FruitA' then key=2; else if key='VeggieB' then key=3; else if key='FruitB' then key=4; else if key='VeggieC' then key=5; else key=6; drop type group; run; %towide(long_recode,wide,first last age,key,1,6,plant,types=C, lengths=20); proc print data=wide (rename=(plant1=VeggieA plant2=FruitA plant3=VeggieB plant4=FruitB plant5=VeggieC plant6=FruitC)); title 'wide'; run; |
proc summary data=long nway; class first last age; output out=wide(drop=_:) idgroup(out[6](plant)=p); run; proc print data=wide (rename=(p_1=VeggieA p_2=FruitA p_3=VeggieB p_4=FruitB p_5=VeggieC p_6=FruitC)); title 'wide'; run; |
Functions referenced:
--- The End ---