Hi there,
Trying to think the best way to do below.. I have multiple records for ID's and each ID has an end state every month ( F or B)
where ID's are always F, i want to tag them as Good. Where always B, I want to tag them as Bad and mixed when it is a mix
Would appreciate any and all inputs
ID | STATE | TYPE |
1 | F | GOOD |
1 | F | GOOD |
1 | F | GOOD |
2 | F | MIXED |
2 | F | MIXED |
2 | F | MIXED |
2 | B | MIXED |
3 | B | BAD |
3 | B | BAD |
3 | B | BAD |
3 | B | BAD |
4 | F | GOOD |
4 | F | GOOD |
4 | F | GOOD |
SQL is nice here, aggregate functions work on character columns. So if the max is equal to the min then all values are the same.
proc sql;
create table want as
select *, case when max(state) = min(state) & max(state)= "F" then "Good"
when max(state) = min(state) & max(state)= "B" then "Bad"
else "MIXED" END as Type
from have
group by ID;
quit;
EDIT: Fixed an issue with the SQL
SQL is nice here, aggregate functions work on character columns. So if the max is equal to the min then all values are the same.
proc sql;
create table want as
select *, case when max(state) = min(state) & max(state)= "F" then "Good"
when max(state) = min(state) & max(state)= "B" then "Bad"
else "MIXED" END as Type
from have
group by ID;
quit;
EDIT: Fixed an issue with the SQL
Thank you so much Reeza and Ksharp,
I combined your solutions because i needed to modify the outcome a bit. I did not know that the sum function could be used this way.
case when max(state) = min(state) & max(state)= "F" then "Good"
when max(state) = min(state) & max(state)= "B" then "Bad"
when sum(state= 'F') > SUM(state= 'B') THEN 'G>B'
when sum(state= 'F') < SUM(state= 'B') THEN 'G<B'
when sum(state= 'F') = SUM(state= 'B') THEN 'G=B'
else '' end as Type
proc sql;
create table type as
select ID,count(ID) as count, sum(state='F') as F, sum(state='B') as B,
case when count(ID) = sum(state='F') then 'GOOD'
when count(ID)=sum(state='B') then 'BAD'
else 'MIXED' end as type
from import1
group by ID;
select i.*, type
from import2 as i
left join type as t
on t.ID=i.ID;
quit;
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
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.