I am trying to divide survey respondents into 4 buckets using IF-THEN-ELSE. I'm not having success.
IF tobacco_pastmo = 0 AND ETOH_pastmo = 0 THEN user_risk = 0; ELSE IF tobacco_pastmo = 1 AND ETOH_pastmo = 0 THEN user_risk = 1; ELSE IF tobacco_pastmo = 0 AND ETOH_pastmo = 1 THEN user_risk = 2; ELSE IF tobacco_pastmo = 1 AND ETOH_pastmo= 1 THEN user_risk = 3; /* 0 = Current MJ only */ /* 1 = Current MJ + Tobacco user */ /* 2 = Current MJ + ETOH user */ /* 3 = Current MJ + Tobacco + ETOH user */
A sample dataset and a screen shot of the results using the syntax above are attached.
Thanks in advance!
The data contains only missing, 1,2, but I think the if statement evaluates it with 0 and 1, so it doesn't get the expected value.
Sorry, I can't access the website holding your PDF. Please paste an image.
Also describe what is wrong (your code looks fine) and include the LOG too.
Your logic if fine, but you can simplify by changing
IF tobacco_pastmo = 0 AND ETOH_pastmo = 0 THEN user_risk = 0;
ELSE IF tobacco_pastmo = 1 AND ETOH_pastmo = 0 THEN user_risk = 1;
ELSE IF tobacco_pastmo = 0 AND ETOH_pastmo = 1 THEN user_risk = 2;
ELSE IF tobacco_pastmo = 1 AND ETOH_pastmo= 1 THEN user_risk = 3;
to (assuming etoh_pastmo and tobacco_pastmo have 3 possible values: missing, 0, and 1:
if nmiss(etoh_pastmo,tobacco_pastmo)=0 then user_risk= 2*etoh_pastmo + tobacco_pastmo
But since the data are really: missing, 1, and 2, then use:
if nmiss(etoh_pastmo,tobacco_pastmo)=0 then user_risk=2*(etoh_pastmo-1) + (tobacco_pastmo-1) ;
> Your logic if fine, but you can simplify by changing
More compact yes, but simpler? This single line of code is A LOT harder to read and to maintain imho.
@ChrisNZ wrote:
> Your logic if fine, but you can simplify by changing
More compact yes, but simpler? This single line of code is A LOT harder to read and to maintain imho.
I can appreciate that observation. But what if there were a 3rd, (or 4th, etc.) dummy variable, doubling the number of categories with each new variable? At some point, I think the (x + 2y + 4z ...) formulation would look more and more appealing compared to 8, 16, .. IF .. THEN statements.
True. To each problem its solution.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.