Download wide.csv 

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

wide.csv preview

*To import the data;

proc import datafile = 'C:/wide.csv' out = wide dbms = csv replace;

getnames = yes;

run;

Option 1: Reshape using proc transpose        

Option 2: Reshape using SAS arrays        

Option 3: Reshape using macro %tolong        

Option 1: Reshape using proc transpose

* Datasets MUST be sorted on ID variable prior to reshaping;

proc sort data=wide;

by first last age;

run;

proc transpose data=wide out=mixed_left1;

by first last age;

var Veggie_A Veggie_B Veggie_C;

run;

proc transpose data=wide out=mixed_left2;

by first last age;

var Fruit_A Fruit_B Fruit_C;

run;

data mixed_left;

merge mixed_left1(rename=col1=Veggie) mixed_left2(rename=col1=Fruit);

by first last age;

Group=scan(_name_,2,'_');

drop _name_;

run;

proc print data=mixed_left;

title 'mixed_left';

run;

reshaped data

Option 2: Reshape using SAS arrays

data mixed_left;

set wide;

array aveggie(1:3) $ Veggie_A Veggie_B Veggie_C;

array afruit(1:3) $ Fruit_A Fruit_B Fruit_C;

do temp=1 to 3;

    Veggie=aveggie(temp);

    Fruit=afruit(temp);

    output;

end;

drop Veggie_A Veggie_B Veggie_C Fruit_A Fruit_B Fruit_C;

run;

data mixed_left;

set mixed_left;

if temp=1 then Group='A';

else if temp=2 then Group='B';

else Group='C';

drop temp;

run;

proc print data=mixed_left;

title 'mixed_left';

run;

reshaped data

Option 3: Reshape using macro %tolong

*rename variables to have numeric suffixes;

data wide_rename;

set wide;

rename Veggie_A=veggie1 Veggie_B=veggie2 Veggie_C=veggie3 Fruit_A=fruit1 Fruit_B=fruit2 Fruit_C=fruit3;

run;

%tolong(wide_rename,mixed_left,first last age,key,1,3,Veggie Fruit, types=C C,lengths=20 20);

data mixed_left;

set mixed_left;

if key=1 then Group='A';

else if key=2 then Group='B';

else Group='C';

drop key;

run;

proc print data=mixed_left;

title 'mixed_left';

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