Download long.csv 

(see “CSV format” under “Files used in the examples”)

long.csv preview

*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        

Option 1: Reshape using proc transpose

* 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;

reshaped data

Option 2: Reshape using SAS arrays

* 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;

reshaped data

Option 3: Reshape using macro %towide

* 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;

reshaped data

Option 4: Reshape using proc summary

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;

reshaped data

Functions referenced:

proc import

proc sort

proc transpose

data step: array

data step: merge

%towide

%tolong

proc summary

proc print

--- The End ---