将SAS字符变量匹配到列表



所以我有一个搜索词向量,和我的主要数据集。我的目标是为主数据集中的每个观测值创建一个指示器,其中variable1至少包含一个搜索词。搜索词和variable1都是字符变量。

目前,我正在尝试使用宏来遍历搜索项,并且对于每个搜索项,指示它是否在变量1中。我不关心哪个搜索词触发了匹配,我只关心有一个匹配(因此我只需要在最后一个指示符变量)。

当涉及到使用SAS宏和循环时,我是一个新手,但我尝试过从一些在线网站搜索和拼凑代码,不幸的是,当我运行它时,它什么也不做,甚至没有给我一个错误。

我已经把我要运行的代码放在下面。

*for example, I am just testing on one of the SASHELP data sets;
*I take the first five team names to create a search list;
data terms; set sashelp.baseball (obs=5);
search_term = substr(team,1,3);
keep search_term;;
run;

*I will be searching through the baseball data set;
data test; set sashelp.baseball;
run;


%macro search;
%local i name_list next_name;
proc SQL;
select distinct search_term into : name_list separated by ' ' from work.terms;
quit;
%let i=1;
%do %while (%scan(&name_list, &i) ne );
%let next_name = %scan(&name_list, &i);

*I think one of my issues is here. I try to loop through the list, and use the find command to find the next_name and if it is in the variable, then I should get a non-zero value returned;
data test; set test;
indicator = index(team,&next_name);
run;
%let i = %eval(&i + 1);
%end;
%mend;

感谢

这是一个完全数据驱动的临时数组解决方案。

  1. 在宏变量中存储项数,用于指定数组的长度
  2. 将搜索项加载到临时数组
  3. 遍历每个单词并搜索术语
  4. 退出循环,如果你找到有助于加快进程的术语
/*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;

我不确定我完全理解你想做什么,但如果你想添加一个新的二进制变量,表明是否有任何子字符串被发现,只需使用如下代码:

data want;
set have;
indicator = index(term,'string1') or index(term,'string2') 
... or index(term,'string27')  ;
run;

不确定什么是"vector";但如果你有数据集中的术语列表,你可以很容易地从数据中生成代码。然后使用%include将其添加到您的程序中。

filename code temp;
data _null_;
set term_list end=eof;
file code ;
if _n_ =1 then put 'indicator=' @ ;
else put ' or ' @;
put 'index(term,' string :$quote. ')' @;
if eof then put ';' ;
run;

data want;
set have;
%include code / source2;
run;

如果你确实想创建一个宏来生成这样的代码,那么宏的参数可能是两个输入数据集名称,两个输入变量名称和输出变量名称。

最新更新