DATA Step, Macro, Functions and more

deleting columns

Accepted Solution Solved
Reply
Contributor
Posts: 72
Accepted Solution

deleting columns

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?


Accepted Solutions
Solution
‎11-09-2016 11:31 PM
Regular Contributor
Posts: 239

Re: deleting 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

View solution in original post


All Replies
Trusted Advisor
Posts: 1,128

Re: deleting columns

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
Solution
‎11-09-2016 11:31 PM
Regular Contributor
Posts: 239

Re: deleting 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

Super User
Super User
Posts: 7,392

Re: deleting 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.

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

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