Monday, April 10, 2017

Hack 4.18 Up-Coding Text Variables with the CHOOSEC Function


SAS Programming Professionals,

Did you know that you can use a SAS function to up-code text variables based on a numeric response variable?

The CHOOSEC function returns a character value that represents the results of choosing from a list of arguments based on the value of an index variable.  The format for the CHOOSEC function is:

CHOOSEC (index-expression, selection-1 <,...selection-n>)

Let’s look at an example:

/* Create example data set */
data class;
set  sashelp.class;

Chip_Response = mod(age, 10);

run;

/* Upcode value of Chip_Response_Text */
data class_Response;
set  class;

length Chip_Response_Text $12.;

Chip_Response_Text = choosec(Chip_Response,"Ruffles", "Lay's", "Kettle", "Miss Vickies", "Pringles", "Don't Know");

run;

The first DATA step simply produces the data set we will be using for the example.  In that DATA step, we create a variable Chip_Response that represents the various subject’s response to the potato chip question in the survey.

The second DATA step uses the CHOOSEC function to assign the correct response text value to Chip_Response_Text, based on the value found in variable Chip_Response.  Chip_Response values of 1 result in Chip_Response_Text values of “Ruffles”, values of 2 result in “Lay’s”, and so forth.  Consequently, Chip_Response_Text ends up containing the correct text value (“Ruffles”, “Lays”, “Kettle”, etc.) as coded in the CHOOSEC function in the DATA step

What’s that?  You are curious as to why I specified a length for Chip_Response_Text instead of letting the length of that variable simply default?  Good question!  I did that because the CHOOSEC function has a nasty habit of assigning variables a length of 200 if the variable is created within the function.  So, keep that caveat in mind when you use the CHOOSEC function in your own programs.

Best of luck in all your SAS endeavors!

---MMMMIIIIKKKKEEEE
(aka Michael A. Raithel)
Author of the new cult classic for computer programmers:  It Only Hurts When I Hit <ENTER>
Print edition:  http://tinyurl.com/z8bzx2e 
Kindle edition: http://tinyurl.com/zypgqa7 

The hack above is an excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers