Hi there,
For your kind information, I am trying to select a group of variables having a particular string as part of its name. For e.g. from my dataset "HAVE", I want only those variable which are having " Completeness" as part of its name.
data have ;
input aa_completeness bb_consistency bb_completeness cc_accuracy cc_completeness dd_consistency;
datalines ;
90 80 70 60 50 40
;
run;
data want ;
input aa_completeness bb_completeness cc_completeness ;
datalines ;
90 70 50
;
run;
Thank you in advance for your kind reply to move forward.
Regards,
A pure data step solution:
filename tmp temp;
data _null_;
file tmp;
if 0 then set have;
length varname $32;
do until (varname='varname');
call vnext(varname);
if index(varname,'_completeness') then put varname;
end;
run;
data want;
set have;
keep
%include tmp;
;
run;
SAS gives you a couple of ways to capture variable names. Here's one:
proc contents data=have noprint out=_contents_ (keep=name);
run;
proc sql;
select strip(name) into : compl_list separated by ' '
from _contents_
where index(upcase(name), 'COMPLETENESS') > 0;
quit;
This should give you a macro variable &COMPL_LIST that holds the names you are looking for. Use as you need to, such as:
data want;
set have (keep=&COMPL_LIST);
run;
Something like the following should work. Note that in the Dictionary table that the variable Libname and Memname (the data set) are in upper case but Name (the variable name) may be mixed. So you want to consider case in comparisons. Any you really want to specify the library as if you have multiple libraries it will find the variables from all data sets with the same name.
proc sql noprint; select name into : varnames separated by " " from dictionary.columns where libname="WORK" and memname="HAVE" and upcase(name) contains "COMPLETENESS"; quit; data want; set have (keep = &varnames); run;
A pure data step solution:
filename tmp temp;
data _null_;
file tmp;
if 0 then set have;
length varname $32;
do until (varname='varname');
call vnext(varname);
if index(varname,'_completeness') then put varname;
end;
run;
data want;
set have;
keep
%include tmp;
;
run;
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.