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 

 

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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