- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
it works!!!!! thank youuu
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;