Hello,
I need to compare multiple variables to each other when the value is not missing (not populated yet). The values across all variables (in this case there are 3) should all be equal and we want to flag when they are not the same.
The challenge is that we do not want to include the missing values in the comparison.
Is there an efficient way to do this without the use of multiple IF THEN and/or missing functions?
Example data layout:
X | Y | Z | FLAG
yes | yes | yes |
no | | no |
yes | no | | Y
| | |
Is it always 'yes','no' or missing of all possible values?
data have;
input (X Y Z) ($) ;
cards;
yes yes yes
no . no
yes no .
;
data want;
set have;
if find(cats(of x--z),'yesno') or find(cats(of x--z),'noyes') then Flag='Y';
run;
Like this?
data HAVE;
X='1'; Y='1'; Z='1'; output;
X=' '; Y='1'; Z='1'; output;
X='2'; Y=' '; Z='1'; output;
X=' '; Y='3'; Z='1'; output;
run;
data WANT;
set HAVE;
ALL=':'||catx(':', of X--Z);
FLAG=missing(tranwrd(ALL,':'||scan(ALL,1,':'),''));
run;
X | Y | Z | FLAG |
---|---|---|---|
1 | 1 | 1 | 1 |
1 | 1 | 1 | |
2 | 1 | 0 | |
3 | 1 | 0 |
Okay , I've been made to wake up
data have;
input (X Y Z) ($) ;
cards;
yes yes yes
no . no
yes no .
;
data want;
set have;
k=coalescec(of x--z);
if count(cats(of x--z),strip(k)) ne countw(catx(' ',of x--z)) then flag='Y';
drop k;
run;
@novinosrin Your method relies on the data being compliant.
The 3 values no nono yes would pass with no Y flag.
data have;
input (X Y Z) ($) ;
cards;
yes yes yes
no . no
yes no .
;
data want;
if _n_=1 then do;
length temp $ 80;
declare hash h();
h.definekey('temp');
h.definedone();
end;
set have;
array _x{*} $ _character_;
do i=1 to dim(_x);
if not missing(_x{i}) then do;temp=_x{i};h.replace();end;
end;
if h.num_items > 1 then flag='Y';
h.clear();
drop i temp;
run;
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.