DATA Step, Macro, Functions and more

reverse transpose -wide to long

Accepted Solution Solved
Reply
Regular Contributor
Posts: 187
Accepted Solution

reverse transpose -wide to long

Hi!  I need some help with a reverse transpose or bring wide to long.

 

i have data like this:

 

NUM GR3 GR4 GR5
1 0 1 0
2 1 0 0
3 0 0 1

 

want to look like this:

 

NUM  GRADE RES
1 GR3 0
  GR4 1
  GR5 0
2 GR3 1
  GR4 0
  GR5 0
3 GR3 0
  GR4 0
  GR5 1

 

Any guidance is appreciated!


Accepted Solutions
Solution
‎04-13-2018 04:11 PM
Super User
Posts: 2,078

Re: reverse transpose -wide to long

data have;
input NUM	GR3	GR4	GR5;
datalines;
1	0	1	0
2	1	0	0
3	0	0	1
;

proc transpose data=have out=want;
by num;
var gr:;
run;

data final_Want;
set want;
by num;
if not first.num then call missing(num);
run;

View solution in original post


All Replies
Solution
‎04-13-2018 04:11 PM
Super User
Posts: 2,078

Re: reverse transpose -wide to long

data have;
input NUM	GR3	GR4	GR5;
datalines;
1	0	1	0
2	1	0	0
3	0	0	1
;

proc transpose data=have out=want;
by num;
var gr:;
run;

data final_Want;
set want;
by num;
if not first.num then call missing(num);
run;
Super User
Posts: 8,220

Re: reverse transpose -wide to long

[ Edited ]

A group of us just presented a macro, at SGF this past Tuesday, that does almost exactly what you want. You can download the macro from: https://github.com/gerhard1050/Untranspose-a-Wide-File

 

Download and run the macro, then run:

%untranspose(data=have, out=want, id=GRADE, id_informat=$3.,
 var_first=N/A,var=RES, by=num)

The only thing it does contrary to your stated WANT is that it assigns the NUM values for each record. I suggest that you do keep the dataset in that form or else you won't be able to sort or analyze the file by NUM.

 

Also, if you actually wanted the variable GRADE to only contain the grade numbers then, instead of running the above macro call, you'd use:

%untranspose(data=have, out=want, id=GRADE, id_informat=1.,
 prefix=GR, var_first=N/A,var=RES, by=num)

Art, CEO, AnalystFinder.com

 

 

Super User
Posts: 13,950

Re: reverse transpose -wide to long

If you want a data set I strongly recommend to NOT have the variable in your NUM role only appear once in a group. That would mean any BY GROUP processing using that variable would be inaccurate at best.

 

So I would likely stop at

proc transpose data=have out=want (rename=(col1=res))
   name=grade 
;
by num;
var gr:;
run;
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 233 views
  • 1 like
  • 4 in conversation