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.
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.