Why is this index not working?
Trying to search for a string inside a variable using index.
Index is in a datastep which is inside a macro.
%MACRO dev_macro;
data class;
set sashelp.class;
%if %eval(%index(lowcase(name),'a')) > 0 %then %do;
result=1;
%end;
%else %do;
result=0;
%end;
run;
%mend dev_macro;
%dev_macro;
Please advise!!
Thank You
Macro functions do not see the values of data step variables. Also macro code is involved with writing code and resolves before the data step even executes. The code generated gets added to the data step before compiling.
So maybe:
%MACRO dev_macro; data class; set sashelp.class; if index(lowcase(name),'a')) > 0 then do; result=1; end; else do; result=0; end; run; %mend dev_macro; %dev_macro;
You don't really describe what the macro should do. So perhaps start with that description. As shown there is no reason to use macro coding at all.
You could simplify this further using the FIND() function but I suspect your root question is actually different.
%MACRO dev_macro;
data class;
set sashelp.class;
if index(lowcase(name)), 'a') > 0 then do;
result=1;
end;
else do;
result=0;
end;
run;
%mend dev_macro;
%dev_macro;
@david27 wrote:
Why is this index not working?
Trying to search for a string inside a variable using index.
Index is in a datastep which is inside a macro.
%MACRO dev_macro; data class; set sashelp.class; %if %eval(%index(lowcase(name),'a')) > 0 %then %do; result=1; %end; %else %do; result=0; %end; run; %mend dev_macro; %dev_macro;
Please advise!!
Thank You
@david27 wrote:
Trying to search for a string inside a variable using index.
Thank You
Then why didn't you use INDEX() in the code?
Your current %INDEX() macro function call is searching for the 'a' in the string lowcase(name)which will return a 0 since there isn't even a one quote character in that string, let alone two of them around the letter a. The %EVAL() macro function call will convert the 0 into a 0. Then the implied %EVAL() will evaluate the comparison 0 > 0 which also return 0 which means FALSE so the %THEN block will be skipped and the %ELSE block will always execute.
So that means you requested that SAS run this data step:
data class;
set sashelp.class;
result=0;
run;
Instead of the data step you probably wanted.
data class;
set sashelp.class;
result= ( 0 < index(lowcase(name),'a') );
run;
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
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.
Ready to level-up your skills? Choose your own adventure.