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 |
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;
something like this
proc transpose data=have out=want(drop =_name_); by studyid ; id code; var value; run;
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;
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;
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;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.