Logical expressions

Logical expressions can appear on the COMPUTE, IF, SELECT IF, DO IF, ELSE IF, LOOP IF, and END LOOP IF commands. A logical expression is evaluated as true or false, or as missing if it is indeterminate. A logical expression returns 1 if the expression is true, 0 if it is false, or system-missing if it is missing. Thus, logical expressions can be any expressions that yield this three-value logic.

  • The simplest logical expression is a logical variable. A logical variable is any numeric variable that has the values 1, 0, or system-missing. Logical variables cannot be strings.
  • Logical expressions can be simple logical variables or relations, or they can be complex logical tests involving variables, constants, functions, relational operators, logical operators, and parentheses to control the order of evaluation.
  • On an IF command, a logical expression that is true causes the assignment expression to be executed. A logical expression that returns missing has the same effect as one that is false--that is, the assignment expression is not executed and the value of the target variable is not altered.
  • On a DO IF command, a logical expression that is true causes the execution of the commands immediately following the DO IF, up to the next ELSE IF, ELSE, or END IF. If it is false, the next ELSE IF or ELSE command is evaluated. If the logical expression returns missing for each of these, the entire structure is skipped.
  • On a SELECT IF command, a logical expression that is true causes the case to be selected. A logical expression that returns missing has the same effect as one that is false--that is, the case is not selected.
  • On a LOOP IF command, a logical expression that is true causes looping to begin (or continue). A logical expression that returns missing has the same effect as one that is false--that is, the structure is skipped.
  • On an END LOOP IF command, a logical expression that is false returns control to the LOOP command for that structure, and looping continues. If it is true, looping stops and the structure is terminated. A logical expression that returns a missing value has the same effect as one that is true--that is, the structure is terminated.

Example

DATA LIST FREE (",") /a.
BEGIN DATA
1, , 1 , ,
END DATA.
COMPUTE b=a.
* The following does NOT work since the second condition
  is never evaluated.
DO IF a=1.
COMPUTE a1=1.
ELSE IF MISSING(a).
COMPUTE a1=2.
END IF.
* On the other hand the following works.
DO IF MISSING(b).
COMPUTE b1=2.
ELSE IF b=1.
COMPUTE b1=1.
END IF.
  • The first DO IF will never yield a value of 2 for a1 because if a is missing, then DO IF a=1 evaluates as missing and control passes immediately to END IF. So a1 will either be 1 or missing.
  • In the second DO IF, however, we take care of the missing condition first; so if the value of b is missing, DO IF MISSING(b) evaluates as true and b1 is set to 2; otherwise, b1 is set to 1.