Hello,
I'm trying to compare the equality of multiple variables in my dataset for each subject. Below is a sample of my data. I need to compare whether the variable PASS is equal for TEST a & b for each subject, then whether the variable LEVEL is equal for that subject for TEST a & b. Then I need to compare whether both variables pass the test for equality. If only one fails, then the variable MATCH (in my want dataset) is set to 'No'.
Dataset
The LAG function is your friend:
data have;
input id test $ pass $ level $ ;
datalines;
1 a 'Yes' 'hard'
1 b 'Yes' 'hard'
2 a 'Yes' 'hard'
2 b 'Yes' 'medium'
3 a 'Yes' 'medium'
3 b 'No' 'medium'
4 a 'Yes' 'hard'
4 b 'Yes' 'hard'
5 a 'No' 'medium'
5 b 'Yes' 'medium'
;
run;
data want;
set have;
by id;
if pass=lag(pass) and level=lag(level) then match='YES';
else match='NO';
if last.id;
run;
The LAG function is your friend:
data have;
input id test $ pass $ level $ ;
datalines;
1 a 'Yes' 'hard'
1 b 'Yes' 'hard'
2 a 'Yes' 'hard'
2 b 'Yes' 'medium'
3 a 'Yes' 'medium'
3 b 'No' 'medium'
4 a 'Yes' 'hard'
4 b 'Yes' 'hard'
5 a 'No' 'medium'
5 b 'Yes' 'medium'
;
run;
data want;
set have;
by id;
if pass=lag(pass) and level=lag(level) then match='YES';
else match='NO';
if last.id;
run;
data have;
input id test $ pass $ level $ ;
datalines;
1 a 'Yes' 'hard'
1 b 'Yes' 'hard'
2 a 'Yes' 'hard'
2 b 'Yes' 'medium'
3 a 'Yes' 'medium'
3 b 'No' 'medium'
4 a 'Yes' 'hard'
4 b 'Yes' 'hard'
5 a 'No' 'medium'
5 b 'Yes' 'medium'
;
run;
proc sql;
create table want as
select Id, case when count(distinct pass)>1 or count(distinct level)>1 then 'NO' else 'YES' end as Match
from have
group by id;
quit;
or the same with ifc
proc sql;
create table want as
select Id, ifc(count(distinct pass)>1 or count(distinct level)>1 ,'NO' ,'YES') as Match
from have
group by id;
quit;
data have;
input id test $ pass $ level $ ;
datalines;
1 a 'Yes' 'hard'
1 b 'Yes' 'hard'
2 a 'Yes' 'hard'
2 b 'Yes' 'medium'
3 a 'Yes' 'medium'
3 b 'No' 'medium'
4 a 'Yes' 'hard'
4 b 'Yes' 'hard'
5 a 'No' 'medium'
5 b 'Yes' 'medium'
;
run;
proc sql;
create table want as
select id,case when count(distinct catx(' ',pass,level))=1 then 'Yes' else 'No ' end as flag
from have
group by id;
quit;
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.