Choosing Rows and Columns
Prerequisites: Conditional logic
Most DATA steps start from an existing data set with SET and keep only
what you need.
WHERE and KEEP
data teens;
set sashelp.class;
where age >= 15;
keep name age height;
run;
proc print data=teens;
run;
Obs Name Age Height
1 Janet 15 62.5
2 Mary 15 66.5
3 Philip 16 72.0
4 Ronald 15 67.0
5 William 15 66.5
WHEREfilters rows as they're read, so rows that don't match never enter the step — efficient for big data sets. It can only test variables that exist in the input.KEEPlists the variables to write;DROPlists the ones to leave out. Columns stay in their original order.
The subsetting IF
An IF with no THEN keeps only rows where the condition is true. Unlike
WHERE, it can test variables you just calculated:
data heavy;
set sashelp.class;
weight_kg = round(weight * 0.4536, 0.1);
if weight_kg > 55;
keep name weight_kg;
run;
proc print data=heavy;
run;
Obs Name weight_kg
1 Philip 68.0
2 Robert 58.1
3 Ronald 60.3
RENAME and data set options
RENAME old=new; renames a variable in the output. Most statements also
exist as data set options in parentheses after a data set name —
(keep=...), (drop=...), (rename=(old=new)), (where=(...)),
(obs=n):
data small;
set sashelp.class(keep=name sex age rename=(sex=gender));
run;
Writing several data sets at once
OUTPUT writes the current row to a data set immediately. Name several
data sets on the DATA statement and choose where each row goes:
data girls boys;
set sashelp.class;
if sex = 'F' then output girls;
else output boys;
run;
Log (abridged):
NOTE: There were 19 observations read from the data set SASHELP.CLASS.
NOTE: The data set WORK.GIRLS has 9 observations and 5 variables.
NOTE: The data set WORK.BOYS has 10 observations and 5 variables.
Once a step contains an explicit OUTPUT, SAS no longer writes rows
automatically at RUN — only your OUTPUT statements do.
Common mistakes
- Using
WHEREon a calculated variable — SAS stops with an error that the variable is not on the input data set. Use a subsettingIF. - Forgetting that
KEEPdoesn't reorder columns. To choose the order, use aRETAINorLENGTHstatement listing them before theSET.