Hello!
I have a dataset that is formatted kind of oddly (but must be in this format to output the way i need it to). Because of that, a simple if/then statement to create a different variable won't do. I have attempted to do a findw and an index of the variable I want to scan for and all that happens is the variable gets overwritten to the last if/then statement. What am I missing (seems fairly simple but i'm missing a piece somewhere). any insight helps. Thanks!
What I want:
vaccine mean goal
dtp_m_w 98 90
dtp_m_e 76 90
opv_m_w 56 80
opv_m_w 75 80
What i'm getting:
vaccine mean goal
dtp_m_w 98 80
dtp_m_e 76 80
opv_m_w 56 80
opv_m_w 75 80
Code I've tried:
data test;
set sample;
if index(vaccine, 'dtp') ne "" then do; goal=90; end;
if index(vaccine, 'opv') ne "" then do; goal=80; end;
run;
i've also tried:
data test;
set sample;
if findw(vaccine, 'dtp') ne "" then goal=90;
if findw(vaccine, 'opv) ne "" then goal=80;
run;
data have;
input vaccine $ mean;* goal ;
cards;
dtp_m_w 98 80
dtp_m_e 76 80
opv_m_w 56 80
opv_m_w 75 80
;
data want;
set have;
if index(vaccine, 'dtp')>0 then goal=90;
if index(vaccine, 'opv')>0 then goal=80;
run;
/*Or*/
data want;
set have;
if index(vaccine, 'dtp') then goal=90;
if index(vaccine, 'opv') then goal=80;
run;
And if the conditions are mutually exclusive i.e DTP and OPV cannot occur in the same value
Use ELSE IF
data want;
set have;
if index(vaccine, 'dtp')>0 then goal=90;
else if index(vaccine, 'opv')>0 then goal=80;
run;
/*Or*/
data want;
set have;
if index(vaccine, 'dtp') then goal=90;
else if index(vaccine, 'opv') then goal=80;
run;
The index function returns a number. It can never return a blank. So your logic using "ne" will always find a match.
Look at the way @novinosrin compared the function results to zero. That's the right comparison.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!
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.
Select SAS Training centers are offering in-person courses. View upcoming courses for: