DATA Step, Macro, Functions and more

Reshape Wide Field to Long

Accepted Solution Solved
Reply
Contributor
Posts: 55
Accepted Solution

Reshape Wide Field to Long

Hi,

I need help to produce the WANT dataset from my HAVE dataset.

data want;
input num code $;
cards;
1 A
1 B
2 C
2 D
;
run;

 

data HAVE;
input num code $;
cards;
1 A,B
2 C,D
;
run;


Accepted Solutions
Solution
‎08-18-2017 11:21 AM
Regular Contributor
Posts: 195

Re: Reshape Wide Field to Long

Posted in reply to angeliquec
No need to use proc transpose. A loop with an output-statement will do:

data want;
set have;
fullCode = code;
do i = 1 to countw(fullCode, ",");
code = scan(fullCode, i, ",");
output;
end;
drop i fullCode;
run;

View solution in original post


All Replies
Super User
Posts: 9,547

Re: Reshape Wide Field to Long

Posted in reply to angeliquec

With a data step and by group processing:

data have;
input num code $;
cards;
1 A
1 B
2 C
2 D
;
run;

data want;
set have (rename=(code=_code));
by num;
retain code "              "; * make long enough to hold all values;
if first.num then code = '';
code = catx(',',code,_code);
if last.num then output;
drop _code;
run;

proc print data=want noobs;
run;

Result:

num    code

 1     A,B 
 2     C,D 

Correct order of dataset have by num is required.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Super Contributor
Posts: 346

Re: Reshape Wide Field to Long

Posted in reply to angeliquec

Another possible solution:

 

data have; 
input num code $;
cards;
1 A,B
2 C,D
;
run;

Data Want;
  Set have;
  Col_1 = Scan(code, 1, ",");
  Col_2 = Scan(code, 2, ",");
  Drop code;
Run;

Proc Transpose Data = Want 
		       Out = Want (Rename=(Col1=code) Drop=_NAME_);
  By num;
  Var Col_1 Col_2; 
Run;
Solution
‎08-18-2017 11:21 AM
Regular Contributor
Posts: 195

Re: Reshape Wide Field to Long

Posted in reply to angeliquec
No need to use proc transpose. A loop with an output-statement will do:

data want;
set have;
fullCode = code;
do i = 1 to countw(fullCode, ",");
code = scan(fullCode, i, ",");
output;
end;
drop i fullCode;
run;
☑ This topic is solved.

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

Discussion stats
  • 3 replies
  • 176 views
  • 0 likes
  • 4 in conversation