SAS (Base SAS)+
data CLASS;
infile datalines dlm='|' dsd missover;
input Name : $8. Sex : $1. Age : best32. Height : best32. Weight : best32.;
label ;
format ;
datalines4;
Alfred|M|14|69|112.5
Alice|F|13|56.5|84
Barbara|F|13|65.3|98
Carol|F|14|62.8|102.5
Henry|M|14|63.5|102.5
James|M|12|57.3|83
;;;;
run;
*------------------------------------------------------------------------------;
*Keep;
*------------------------------------------------------------------------------;
data subset;
set class;
keep Name Sex Age;
run;
*------------------------------------------------------------------------------;
*drop;
*------------------------------------------------------------------------------;
data subset;
set class;
drop height weight;
run;
*------------------------------------------------------------------------------;
*drop - pattern;
*------------------------------------------------------------------------------;
data subset;
set class;
drop h: w:;
run;
infile datalines dlm='|' dsd missover;
input Name : $8. Sex : $1. Age : best32. Height : best32. Weight : best32.;
label ;
format ;
datalines4;
Alfred|M|14|69|112.5
Alice|F|13|56.5|84
Barbara|F|13|65.3|98
Carol|F|14|62.8|102.5
Henry|M|14|63.5|102.5
James|M|12|57.3|83
;;;;
run;
*------------------------------------------------------------------------------;
*Keep;
*------------------------------------------------------------------------------;
data subset;
set class;
keep Name Sex Age;
run;
*------------------------------------------------------------------------------;
*drop;
*------------------------------------------------------------------------------;
data subset;
set class;
drop height weight;
run;
*------------------------------------------------------------------------------;
*drop - pattern;
*------------------------------------------------------------------------------;
data subset;
set class;
drop h: w:;
run;
- To keep specific variables, we add a
keepstatement inside the DATA step:keep Name Sex Age;. - To drop variables instead, we use
drop height weight;. The effect is the opposite — SAS writes every variable except the listed ones. - For pattern-based dropping, SAS supports the colon shorthand:
drop h: w:;drops every variable whose name starts with h or w. - We can mix
keepanddropstatements or even use dataset-option forms likeset class (drop=height weight);when we want the subset to happen at theSETstage. - The output dataset has the same rows as the input but only the selected columns.