## Convert from Long to Wide

Solved
Regular Contributor
Posts: 150

# Convert from Long to Wide

I have a dataset in long format, example below: I need to convert it to one observation per person with the codes as the variables names and the value as the values for each person. So I would end up with 7 variables: studyid and S01-S06. Any help to do this would be appreciate!

 studyid code value 27 S01 3.25 27 S02 2.75 27 S03 2.75 27 S04 2.75 27 S05 2.75 27 S06 2.75 28 S01 2.75 28 S02 2.75 28 S03 2.5 28 S04 2.75 28 S05 2.75 28 S06 2.75 29 S01 2 29 S02 2 29 S03 2.5 29 S04 2.5 29 S05 2.5 29 S06 2

Accepted Solutions
Solution
‎06-13-2017 11:47 AM
Frequent Contributor
Posts: 80

## Re: Convert from Long to Wide

DATA HAVE;
INPUT Studyid code\$3.value;
DATALINES;
27 S01 3.25
27 S02 2.75
27 S03 2.75
27 S04 2.75
27 S05 2.75
27 S06 2.75
28 S01 2.75
28 S02 2.75
28 S03 2.5
28 S04 2.75
28 S05 2.75
28 S06 2.75
29 S01 2
29 S02 2
29 S03 2.5
29 S04 2.5
29 S05 2.5
29 S06 2
;
RUN;

PROC SORT DATA= HAVE ;BY Studyid CODE;RUN;

PROC TRANSPOSE DATA=HAVE

OUT=WANT (DROP=_NAME_);
BY Studyid;

ID code;

VAR value;

RUN;

All Replies
PROC Star
Posts: 549

## Re: Convert from Long to Wide

[ Edited ]

something like this

```proc transpose data=have out=want(drop =_name_);
by studyid ;
id code;
var value;
run;```
Posts: 1,163

## Re: Convert from Long to Wide

alternatively please try arrays, but have to create a numeric variable num  before

``````data have;
input studyid 	code\$ 	value;
num=input(compress(code,,'kd'),best.);
cards;
27 	S01 	3.25
27 	S02 	2.75
27 	S03 	2.75
27 	S04 	2.75
27 	S05 	2.75
27 	S06 	2.75
28 	S01 	2.75
28 	S02 	2.75
28 	S03 	2.5
28 	S04 	2.75
28 	S05 	2.75
28 	S06 	2.75
29 	S01 	2
29 	S02 	2
29 	S03 	2.5
29 	S04 	2.5
29 	S05 	2.5
29 	S06 	2
;

data want;
set have;
by studyid;
retain s01-s06;
array s(6) s01-s06;
if first.studyid then call missing(of s(*));
s(num)=value;
if last.studyid;
run;``````

Thanks,
Jag
Posts: 1,163

## Re: Convert from Long to Wide

using arrays and without the num variable from code we could try

``````data want;
set have;
by studyid;
retain s01-s06;
array s(*) s01-s06;
if first.studyid then call missing(of s(*));
if first.studyid then i=1;
else i+1;
s(i)=value;
if last.studyid;
run;``````
Thanks,
Jag
Solution
‎06-13-2017 11:47 AM
Frequent Contributor
Posts: 80

## Re: Convert from Long to Wide

DATA HAVE;
INPUT Studyid code\$3.value;
DATALINES;
27 S01 3.25
27 S02 2.75
27 S03 2.75
27 S04 2.75
27 S05 2.75
27 S06 2.75
28 S01 2.75
28 S02 2.75
28 S03 2.5
28 S04 2.75
28 S05 2.75
28 S06 2.75
29 S01 2
29 S02 2
29 S03 2.5
29 S04 2.5
29 S05 2.5
29 S06 2
;
RUN;

PROC SORT DATA= HAVE ;BY Studyid CODE;RUN;

PROC TRANSPOSE DATA=HAVE

OUT=WANT (DROP=_NAME_);
BY Studyid;

ID code;

VAR value;

RUN;

☑ This topic is solved.