I have some data that I would like to print or plot. I would like the output grouped by a certain variable. I can do this like this:
data test;
proc print; by source;
proc means; by source;
In my example source can be a single letter 'A', 'B', 'C', or 'D'. I would like to specify the order of the groups. I don't want it to be
alphabetical. I might want the order to be 'C', 'B', 'D', 'A'. Is there a way to do this?
Hi ... never tried this before, but it appears to do what you asked ...
proc trantab table=ascii;
replace 'C' '1' ;
replace 'B' '2';
replace 'D' '3';
replace 'A' '4';
save table=test;
quit;
data x;
do _n_ = 1 to 1000;
letter = char('ABCD',rantbl(999,.25,.25,.25));
x = ceil(1000*ranuni(999));
output;
end;
run;
proc sort data=x sortseq=test;
by letter;
run;
proc means data=x;
by letter;
run;
There might be a more direct method I can't think of at the moment, but you can always create an informat, apply it, and then use it as your by variable. e.g.:
proc format;
invalue $names
'Henry'=1
'Alice'=2
'James'=3
'Jane'=4
other=5;
run;
data test;
set sashelp.class;
sortnames=input(name,$names.);
run;
proc sort data=test;
by sortnames;
run;
proc print data=test (
drop=name rename=(sortnames=name));
by name;
run;
Art. it should be
proc format;
invalue names
Not include Dollar sign because it is numeric informat not character.
I know SAS passed this fragment code. But I recommend to not use $.
Ksharp
Thanks Art. However, the output of your example includes name=1, name=2, etc. Is there a way to show the original names in the output instead of the value we are using to specify their order?
I don't know about "instead of", but I do know how to get "in addition to."
proc sort data=test;
by sortnames name;
run;
proc print data=test ;
by sortnames name;
run;
This should at least put both in the byvar header block.
Steve Denham
Hi ... never tried this before, but it appears to do what you asked ...
proc trantab table=ascii;
replace 'C' '1' ;
replace 'B' '2';
replace 'D' '3';
replace 'A' '4';
save table=test;
quit;
data x;
do _n_ = 1 to 1000;
letter = char('ABCD',rantbl(999,.25,.25,.25));
x = ceil(1000*ranuni(999));
output;
end;
run;
proc sort data=x sortseq=test;
by letter;
run;
proc means data=x;
by letter;
run;
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.