So far, all of our examples have pertained to numeric variables. Now, let's take a look at adding a new character variable to your data set or modifying an existing characteric variable in your data set. In the previous lessons, we learned how to read the values of a character variable by putting a dollar sign ($) after the variable's name in the INPUT statement. Now, you can update a character variable (or create a new character variable!) by specifying the variable's values in an assignment statement.
Example 4.9 Section
When creating a new character variable in a data set, most often you will want to assign the values based on certain conditions. For example, suppose an instructor wants to create a character variable called status which indicates whether a student "passed" or "failed" based on their overall final grade. A grade below 65, say, might be considered a failing grade, while a grade of 65 or higher might be considered a passing grade. In this case, we would need to make use of an if-then-else statement. We'll learn more about this kind of statement in the next lesson, but you'll get the basic idea here. The following SAS program illustrates the creation of a new character variable called status using an assignment statement in conjunction with an if-then-else statement:
DATA grades; input name $ 1-15 e1 e2 e3 e4 p1 f1; * calculate the average using the mean function; avg = mean(e1,e2,e3,e4); * if the average is less than 65 indicate failed, otherwise indicate passed; if (avg < 65) then status = 'Failed'; else status = 'Passed'; DATALINES; Alexander Smith 78 82 86 69 97 80 John Simon 88 72 86 . 100 85 Patricia Jones 98 92 92 99 99 93 Jack Benedict 54 63 71 49 82 69 Rene Porter 100 62 88 74 98 92 ; RUN; PROC PRINT data = grades; var name e1 e2 e3 e4 avg status; RUN;
Launch and run the SAS program. Review the output from the PRINT procedure to convince yourself that the values of the character variable status have been assigned correctly. As you can see, to specify a character variable's value using an assignment statement, you enclose the value in quotes. Some comments:
- You can use either single quotes or double quotes. Change the single quotes in the above program to double quotes, and re-run the SAS program to convince yourself that the character values are similarly assigned.
- If you forget to specify the closing quote, it is typically a show-stopper as SAS continues to scan the program looking for the closing quote. Delete the closing quote in the above program, and re-run the SAS program to convince yourself that the program fails to accomplish what is intended. Check your log window to see what kind of a warning statement is generated.