Help using Base SAS procedures

Learning SAS...would like some help with an exercise on Proc Transpose

Reply
Occasional Contributor
Posts: 9

Learning SAS...would like some help with an exercise on Proc Transpose

Hi, just wondering if anyone can provide some help on this SAS exercise I'm working on using Proc Transpose. Here is my code:

data test;
input sid score year;
cards;
1 89 2001
2 88 2001
1 92 2002
2 98 2003
1 99 2004
2 89 2004
;
run;

proc sort data=test;
by sid;
run;

proc transpose data=test out=test2 prefix=year;
var score;
by sid;
id year;
run;

proc print data=test2;
run;

Here is the output (looks a little weird in this thread but you get the idea):

Obs sid _NAME_ year2001 year2002 year2004 year2003

1 1 score 89 92 99 .
2 2 score 88 . 89 98


in the output, the values for variable year would become variables themselves but year2004 is before year2003. How do I put year2003 before year2004. What modifications do I need to make to my code in order to do this?

Thanks!
PROC Star
Posts: 7,363

Re: Learning SAS...would like some help with an exercise on Proc Transpose

Kyle,

I'm not sure if there is any option that can do what you want, but you can always reorder the variables after having run proc transpose. For example, the following will do just that if run after the statements shown in your example:
[pre]
proc sql noprint;
select strip(name) into :vars separated by ' '
from dictionary.columns
where libname="WORK" and memname="TEST2"
order by 1
;
quit;

data want;
retain &vars.;
set test2;
run;
[/pre]
HTH,
Art
Super Contributor
Super Contributor
Posts: 365

Re: Learning SAS...would like some help with an exercise on Proc Transpose

Hello KyleS83,

In you case the simpliest way is to add one more datastep:
[pre]
data test2;
retain sid _NAME_ year2001-year2004;
set test2;
run;
[/pre]
Sincerely,
SPR
Super User
Posts: 9,682

Re: Learning SAS...would like some help with an exercise on Proc Transpose

[pre]
data test;
input sid score year;
cards;
1 89 2001
2 88 2001
1 92 2002
2 98 2003
1 99 2004
2 89 2004
;
run;
proc sql ;
create table temp as
select *
from (select distinct sid from test),(select distinct year from test)
;

create table op as
select temp.*,score
from temp left join test on temp.sid = test.sid and temp.year = test.year
;
quit;
proc transpose data=op out=want prefix=year;
by sid;
id year;
var score;
run;
[/pre]

Ksharp
Ask a Question
Discussion stats
  • 3 replies
  • 115 views
  • 0 likes
  • 4 in conversation