Question

How do I reshape this data in SAS?

id  q1a q2a q1b q2b q1c q2c
1   3   0   1   1   1   9
2   4   9   1   2   2   0
3   5   9   1   2   4   0

into this:

id  q1  q2 type
1   3   0   a
1   1   1   b
1   1   9   c
.............
Was it helpful?

Solution

The simplest way is to transpose the data, split out the last letter from the q variables, then re-transpose.

data have;
input id  q1a q2a q1b q2b q1c q2c;
datalines;
1   3   0   1   1   1   9
2   4   9   1   2   2   0
3   5   9   1   2   4   0
;
run;

proc transpose data=have out=temp1;
by id;
run;

data temp2;
set temp1;
length type $1;
type=substr(_NAME_,3);
_NAME_=substr(_NAME_,1,2);
run;

proc transpose data=temp2 out=want (drop=_:) ;
by id type;
id _NAME_;
var COL1;
run;

OTHER TIPS

Seems simpler to me to just do it in one bit.

data want;
set have;
array qs q:;
do _t = 1 to dim(qs) by 2;
  q1=qs[_t];
  q2=qs[_t+1];
  type = substr(vname(qs[_t]),3,1);
  output;
end;
keep id q1 q2 type;
run;

That works for exactly your data; there are some assumptions (the substr and the relationship between q1/q2) that might need to be changed for a real-world example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top