Hi,
I have several data sets that look like:
Obs v1 v2 v3
1 2 3 3
2 5 3 2
3 1 0 3
etc
;
And would like to move the columns to rows:
Obs v
1 2
2 5
3 1
1 3
2 3
3 0
1 3
2 2
3 3
etc
;
Is there a simple way to do this in data step (instead of using transpose or other procedures)?
Thanks for assistance with this.
Jason
Why not use the best tool for the job, i.e. proc transpose?
In a data step, put V1-V3 in an array and output each value in a do LOOP.
data have;
input Obs v1 v2 v3;
cards;
1 2 3 3
2 5 3 2
3 1 0 3
;
;
run;
proc transpose data=have out=_h;
by _all_;
var v:;
run;
proc sort data=_h out=want(keep=col1);
by _name_;
run;
I know that I could use transpose. However, because the data set has other variables that I want be copied (not transposed) to the vertical output set I thought using the data step is less complicated.
ok PG's suggested, loop and array should suffice
If you are really interested in changing just 3 variables, here's a very simple way:
data want;
set have;
v=v1;
output;
v=v2;
output;
v=v3;
output;
drop v1 v2 v3;
run;
If you actually have more than 3 variables, putting them into an array (as was suggested) is an excellent idea.
Thanks to all. All your replies were very useful. I appreciate it.
Jason
Did I missed something ?
data have;
input Obs v1 v2 v3;
cards;
1 2 3 3
2 5 3 2
3 1 0 3
;
data want;
set have(keep=obs v1 rename=(v1=v))
have(keep=obs v2 rename=(v2=v))
have(keep=obs v3 rename=(v3=v));
run;
Just a small point. In reality, the KEEP list is longer. You would either need to spell out a longer list, or switch to:
set have (drop=v2 v3 rename=(v1=v))
have (drop=v1 v3 rename=(v2=v))
have (drop=v1 v2 rename=(v3=v));
Astounding,
You mean you save more code than me ?
Sort of. Buried in one of the messages is that OBS represents many variables, not just a single variable. The message didn't say how many, but if there were 30 variables that needed to be carried to the output, they all would need to appear in the KEEP list.
OK. I know you .
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.