Download mixedR.csv 

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

mixedR.csv preview

*To import the data;

proc import datafile = 'C:/mixedR.csv' out = mixed_right 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=mixed_right;

by first last age;

run;

proc transpose data=mixed_right out=wide1 suffix=A;

by first last age;

id type;

var A;

run;

proc transpose data=mixed_right out=wide2 suffix=B;

by first last age;

id type;

var B;

run;

proc transpose data=mixed_right out=wide3 suffix=C;

by first last age;

id type;

var C;

run;

data wide;

merge wide1(drop=_name_) wide2(drop=_name_) wide3(drop=_name_);

by first last age;

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=mixed_right;

by first last age;

run;

data wide;

set mixed_right;

by first last age;

keep first last age VeggieA VeggieB VeggieC FruitA FruitB FruitC;

retain VeggieA VeggieB VeggieC FruitA FruitB FruitC;

if type='Veggie' then type=1;

else type=2;

array aA(1:2) $ VeggieA FruitA;

array aB(1:2) $ VeggieB FruitB;

array aC(1:2) $ VeggieC FruitC;

if first.type then do;

    do i=1 to 2;

            aA(i)='';

            aB(i)='';

            aC(i)='';

    end;

end;

aA(type)=A;

aB(type)=B;

aC(type)=C;

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

set mixed_right;

if type='Veggie' then type=1;

else type=2;

run;

%towide(mixed_right_recode,wide,first last age,type,1,2,A B C,types=C C C,lengths=20 20 20);

data wide;

set wide;

rename A1=VeggieA A2=FruitA B1=VeggieB B2=FruitB C1=VeggieC C2=FruitC;

run;

proc print data=wide;

title 'wide';

run;

reshaped data

Option 4: Reshape using proc summary

proc summary data=mixed_right nway;

class first last age;

output out=wide(drop=_:)

idgroup(out[2](A)=A)

idgroup(out[2](B)=B)

idgroup(out[2](C)=C);

run;

proc print data=wide

(rename=(A_1=VeggieA A_2=FruitA B_1=VeggieB B_2=FruitB C_1=VeggieC C_2=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 ---