PROC PRINT and PROC SORT
Prerequisites: Choosing rows and columns
Sorting
PROC SORT reorders a data set by one or more BY variables. Use OUT=
to write a sorted copy; without it, the input data set is replaced.
proc sort data=sashelp.class out=tallest;
by descending height;
run;
proc print data=tallest(obs=5) noobs;
var name sex height;
format height 5.1;
run;
Name Sex Height
Philip M 72.0
Alfred M 69.0
Ronald M 67.0
Mary F 66.5
William M 66.5
DESCENDINGapplies to the variable right after it.- Rows with equal values keep their original order (Mary comes before
William in
SASHELP.CLASS). - You can't write into
SASHELP— it's read-only, which is whyOUT=is needed here.
Sort by several variables — the second breaks ties in the first:
proc sort data=sashelp.class out=by_sex_age;
by sex descending age;
run;
NODUPKEY removes rows with duplicate BY values — handy for getting one
row per key.
Printing
title 'Students aged 12';
proc print data=sashelp.class label noobs;
where age = 12;
var name height weight;
label height = 'Height (in)' weight = 'Weight (lb)';
run;
title;
Students aged 12
Height Weight
Name (in) (lb)
James 57.3 83.0
Jane 59.8 84.5
John 59.0 99.5
Louise 56.3 77.0
Robert 64.8 128.0
VARchooses and orders the columns.WHEREworks in procedures too.LABELshows descriptive column headings (PROC PRINT needs theLABELoption to use them).NOOBShides theObscolumn.TITLEstays in effect for every later step until you change it;title;clears it.
Totals by group
With data sorted by a variable, BY prints a separate section per group,
and SUM adds totals:
proc sort data=sashelp.class out=sorted;
by sex;
run;
proc print data=sorted noobs;
by sex;
var name weight;
sum weight;
run;
Each section ends with the group total, and a grand total appears at the end: 811.0 pounds for the girls, 1,089.5 for the boys, and 1,900.5 in all.
Practice
Print the three lightest students — name, age, and weight — with a title.
Show solution
proc sort data=sashelp.class out=lightest;
by weight;
run;
title 'Three lightest students';
proc print data=lightest(obs=3) noobs;
var name age weight;
format weight 5.1;
run;
title;
Three lightest students
Name Age Weight
Joyce 11 50.5
Louise 12 77.0
James 12 83.0