Skip to content

Instantly share code, notes, and snippets.

@statgeek
Created September 16, 2021 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statgeek/2f733d27820f43fa37d6ba92c30f22cf to your computer and use it in GitHub Desktop.
Save statgeek/2f733d27820f43fa37d6ba92c30f22cf to your computer and use it in GitHub Desktop.
SAS - temporary array - word/term search with multiple words
/*This is an example of how to search through a list of terms and see if a field contains any of the values*/
*Make fake data to show example;
*terms to search for;
data terms;
set sashelp.baseball (obs=5);
search_term = substr(team,1,3);
keep search_term;;
run;
*main data set that will be searched;
data test;
set sashelp.baseball;
run;
/*General process to the solution*/
******************************************************************************************
1. Store the number of terms in a macro variable to assign the length of arrays
2. Load terms to search into a temporary array
3. Loop through for each word and search the terms
4. Exit loop if you find the term to help speed up the process
******************************************************************************************;
/*1*/
proc sql noprint;
select count(*) into :num_search_terms from terms;
quit;
%put &num_search_terms.;
data flagged;
*declare array;
array _search(&num_search_terms.) $ _temporary_;
/*2*/
*load array into memory;
if _n_ = 1 then do j=1 to &num_search_terms.;
set terms;
_search(j) = search_term;
end;
set test;
*set flag to 0 for initial start;
flag = 0;
/*3*/
*loop through and craete flag;
do i=1 to &num_search_terms. while(flag=0); /*4*/
if find(team, _search(i), 'it')>0 then flag=1;
end;
drop i j search_term ;
run;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment