2 if — if programming command
Example 1
Do not confuse the if command with the if qualifier. Typing if (age>21) summarize age will
summarize all the observations on age if the first observation on age is greater than 21. Otherwise,
it will do nothing. Typing summarize age if age>21, on the other hand, summarizes all the
observations on age that are greater than 21.
Example 2
if is typically used in do-files and programs. For instance, let’s write a program to calculate the
Tukey (1977, 90–91) “power” function of a variable, x:
. program power
if ‘2’>0 {
generate z=‘1’^‘2’
label variable z "‘1’^‘2’"
}
else if ‘2’==0 {
generate z=log(‘1’)
label variable z "log(‘1’)"
}
else {
generate z=-(‘1’^(‘2’))
label variable z "-‘1’^(‘2’)"
}
end
This program takes two arguments. The first argument is the name of an existing variable, x.
The second argument is a number, which we will call n. The program creates the new variable z. If
n > 0, z is x
n
; if n = 0, z is log x; and if n < 0, z is −x
n
. No matter which path the program
follows through the code, it labels the variable appropriately:
. power age 2
. describe z
storage display value
variable name type format label variable label
z float %9.0g age^2
Technical note
If the expression refers to any variables, their values in the first observation are used unless explicit
subscripts are specified.
Avoid single-line if and else with ++ and -- macro expansion
Do not use the single-line forms of if and else—do not omit the braces—when the action
includes the ‘++’ or ‘--’ macro-expansion operators. For instance, do not code
if (. . . ) somecommand ‘++i’