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
IFcommand, 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 IFcommand, a logical expression that is true causes the execution of the commands immediately following theDO IF, up to the nextELSE IF,ELSE, orEND IF. If it is false, the nextELSE IForELSEcommand is evaluated. If the logical expression returns missing for each of these, the entire structure is skipped. - On a
SELECT IFcommand, 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 IFcommand, 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 IFcommand, a logical expression that is false returns control to theLOOPcommand 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 IFwill never yield a value of 2 for a1 because if a is missing, thenDO IF a=1evaluates as missing and control passes immediately toEND 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.