BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Jahanzaib
Quartz | Level 8

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?

1 ACCEPTED SOLUTION

Accepted Solutions
RahulG
Barite | Level 11
%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

View solution in original post

3 REPLIES 3
Jagadishkatam
Amethyst | Level 16
Please get the details of the variables in the dataset by

proc contents data=x out=vars;
run;

After this sort the data by order of the variables with VARNUM

proc sort data=vars;
by varnum;
run;

create a macro variable keep from proc sql

proc sql;
select name into:keep from vars where varnum<=7;
quit;

%put &keep;

Use this keep macro variable to keep only the required variables.
Thanks,
Jag
RahulG
Barite | Level 11
%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

RW9
Diamond | Level 26 RW9
Diamond | Level 26

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-wordmark-2025-midnight.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.


Register now!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 16004 views
  • 4 likes
  • 4 in conversation