I have data which include around 20-25 columns. I want to keep only first 7 columns and delete the remaining. How can i do that?
%let no_of_col=7;
/* Sample dataset cars considered for code */
data cars;
set sashelp.cars;
run;
/* column list extracted */
proc contents data=cars out=column_nm varnum;
run;
proc sort data=column_nm out=col_nm_sorted(keep = libname memname name);
by varnum;
run;
data filtered_col;
set col_nm_sorted(obs=&no_of_col);
run;
proc sql noprint;
select name into :_col_name separated by ' '
from filtered_col;
quit;
%put &_col_name ;
data want;
set cars (keep = &_col_name);
run;
I have taken work.cars as an input dataset and kept first 7 columns
%let no_of_col=7;
/* Sample dataset cars considered for code */
data cars;
set sashelp.cars;
run;
/* column list extracted */
proc contents data=cars out=column_nm varnum;
run;
proc sort data=column_nm out=col_nm_sorted(keep = libname memname name);
by varnum;
run;
data filtered_col;
set col_nm_sorted(obs=&no_of_col);
run;
proc sql noprint;
select name into :_col_name separated by ' '
from filtered_col;
quit;
%put &_col_name ;
data want;
set cars (keep = &_col_name);
run;
I have taken work.cars as an input dataset and kept first 7 columns
The simplest way is to use list operator in SAS:
data want; set have (keep=<first>--<last>); run;
Replace <first> with the variable to start from and <last> with the last one - you of course know what these are as it is your data. I would not rely on order of columns in the dataset - that can change very easliy and then you get different results.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.