Just convert your logic into SAS statements.
data want;
set have;
length varc $4 ;
if VarA=1 and VarB=1 then VarC = "Both";
else if VarA=2 and VarB=2 then VarC = "None";
else if VarA=1 and VarB=2 then VarC = "VarA";
else if VarA=2 and VarB=1 then VarC = "VarB" ;
run;
If you just put AND between two variables then SAS just test if the value of the variable is true or false. SAS will treat any values of VARA that are zero or missing as FALSE and any other value as TRUE. So your first two conditions as you wrote them were just testing the value of VARB since either 1 or 2 in VARA would be considered TRUE.
Thank you.
For your first two sets of conditions, this would also work:
if VarA = VarB = 1 then VarC = "Both";
else if VarA = VarB = 2 then VarC = "None";
Another approach (untested)
proc format;
value $C
"11"="Both"
"22"="None"
"12"="VarA"
"21"="VarB"
;
run;
data want;
set have;
length varc $2 ;
VarC=cats(put(VarA,$1.),put(VarB,$1.));
format VarC $C.;
/*
if VarA=1 and VarB=1 then VarC = "Both";
else if VarA=2 and VarB=2 then VarC = "None";
else if VarA=1 and VarB=2 then VarC = "VarA";
else if VarA=2 and VarB=1 then VarC = "VarB" ;
*/
run;
Interesting, thank you.
To elaborate a little on the solution by @Tom:
Data want;
set have;
if VarA=1 then do;
if VarB=1 then VarC='Both';
else VarC='VarA';
end;
else if VarB=1 then
VarC='VarB';
else
VarC='None';
run;
This runs slightly faster, as you do not repeatedly test the same condition. The results can be different if you have other categories than 1 and 2 (everything but 1 is considered "not-one" and treated like a 2), @Tom 's solution will leave such exceptions blank.
If you want to explicitly test for such category errors and flag them, it can be done like this:
data want;
set have;
select(catx(VarA,VarB));
when('11') VarC='Both';
when('12') VarC='VarA';
when('21') VarC='VarB';
when('11') VarC='None';
otherwise VarC='Err';
end;
run;
If you leave out the OTHERWISE statement, the program will fail (log error) if there are other values than 1 or 2. Which may be what you want in that case.
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.