BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
meetagupta
Fluorite | Level 6

If I have a SAS dataset with the following values. I want to create a new variable and assign value"A" if cust_id is there 2 times in the table and assign value "B" if cust_id is there 3 times. For ex. For cust_id=1113, I want new variable value to be A and for cust_id=1115, I want new variable value to be B. 

Thanks.

 

cust_id   month

1112       Mar

1113       apr

1113       feb

1114        feb

1115        mar

1115       apr

1115        feb

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20
data have;
input cust_id $   month $;
cards;
1112       Mar
1113       apr
1113       feb
1114        feb
1115        mar
1115       apr
1115        feb
;

proc sql;
create table want as
select *,case when count(cust_id)=2 then 'A' 
when count(cust_id)=3 then 'B' else ' ' end as New_var
from have
group by cust_id;
quit;

View solution in original post

4 REPLIES 4
PeterClemmensen
Tourmaline | Level 20

What if it's there 1 or 4 times?

meetagupta
Fluorite | Level 6

they can be set to missing..

novinosrin
Tourmaline | Level 20
data have;
input cust_id $   month $;
cards;
1112       Mar
1113       apr
1113       feb
1114        feb
1115        mar
1115       apr
1115        feb
;

proc sql;
create table want as
select *,case when count(cust_id)=2 then 'A' 
when count(cust_id)=3 then 'B' else ' ' end as New_var
from have
group by cust_id;
quit;
PeterClemmensen
Tourmaline | Level 20

Ok. Do something like this

data have;
input cust_id month $;
datalines;
1112 Mar
1113 apr
1113 feb
1114 feb
1115 mar
1115 apr
1115 feb
;

data want;
   do _N_=1 by 1 until (last.cust_id);
      set have;
      by cust_id;
   end;
   do until (last.cust_id);
      set have;
      by cust_id;
      if      _N_=2 then newValue='A';
      else if _N_=3 then newValue='B';
      output;
   end;
run;

 

Result:

 

cust_id month newValue 
1112    Mar     
1113    apr   A 
1113    feb   A 
1114    feb     
1115    mar   B 
1115    apr   B 
1115    feb   B 

 

sas-innovate-wordmark-2025-midnight.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.


Register now!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 882 views
  • 2 likes
  • 3 in conversation