BookmarkSubscribeRSS Feed
curious_guy
Calcite | Level 5

Hi SAS Master, 

 

I want to ask, how to simplify this IF-ELSE statement on SAS. Below is the code:

 

data test;
if 	year = 0 then bucket = 'M0 ';
else if year = 1 then bucket = 'M1 ';
else if year = 2 then bucket = 'M2 ';
else if year = 3 then bucket = 'M3 ';
else if year = 4 then bucket = 'M4 ';
else if year = 5 then bucket = 'M5 ';
else if year = 6 then bucket = 'M6 ';
else bucket = 'WO' ;
run;

 

feel free to format the bucket whether this char or numeric. 

thank you.

3 REPLIES 3
ballardw
Super User

Actually no if/then/else is needed depending on how you intend to use those W0, W1 etc values.

 

For many purposes you could create a custom format:

proc format;
  value myear
0='M0'
1='M1'
2='M2'
3='M3'
4='M4'
5='M5'
6='M6'
other = 'WO'
;
run;

Then assign the format Myear to the Year variable. Such as

Proc print data=have;
   var year;
   format year myear. ;
run;

 

The groups created by formats are honored by reporting and analysis procedures and graphing for many simple formats like this.

The only complexity involved is making sure the format is available when needed, such as running the proc format code in each session before use.

 

Or if you really want a data step solution:

if year in (0:6) then bucket=cats('M',year);
else bucket='WO';

The IN checks to see if year is one of the listed integer values from 0 to 6 and if so uses the CATS function to append the year value to the letter M.

 

 

 

curious_guy
Calcite | Level 5

it works!!!!! thank youuu

andreas_lds
Jade | Level 19

You could use select/when or use the format show by @ballardw in a data step. If you need to the re-coding in multiple places, using a format is my preferred technique, because you have the definition in one place. Easier to read is the second way shown by ballardw, but whether such way exists depends largely on the re-coding itself.

 

data want;
  set have;
  
  bucket = put(year, myear.);
run;

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

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
  • 3 replies
  • 1048 views
  • 0 likes
  • 3 in conversation