5.1 - If-Then Statements5.1 - If-Then Statements
In this lesson, we investigate a number of examples that illustrate how to change a subset of the observations in our data set. In SAS, the most common way to select observations that meet a certain condition is to utilize an if-then statement. The basic form of the statement is:
IF (condition is true) THEN (take this action);
In the previous lesson, we looked at an example in which the condition was:
avg < 65
and the action was:
status = 'Failed'
For each observation, SAS evaluates the condition that follows the keyword IF — in this case, is the student's average less than 65? — to determine if it is true or false. If the condition is true, SAS takes the action that follows the keyword THEN — in this case, change the student's status to 'Failed.' If the conditon is false, SAS ignores the THEN clause and proceeds to the next statement in the DATA step. The condition always involves a comparison of some sort, and the action taken is typically some sort of assignment statement.
There is nothing really new here. You've already seen an if-then(-else) statement in the previous lesson. Our focus there was primarily on the assignment statement. Here, we'll focus on the entire if-then statement, including the condition. The following SAS program creates a character variable status, whose value depends on whether or not the student's first exam grade is less than 65:
DATA grades; input name $ 1-15 e1 e2 e3 e4 p1 f1; * if the first exam is less than 65 indicate failed; if (e1 < 65) then status = 'Failed'; 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 status; RUN;
First, note that we continue to work with the grades data set from the last lesson. Again, the data set contains student names (name), each of their four exam grades (e1, e2, e3, e4), their project grade (p1), and their final exam grade (f1). Then, 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.