Stata Logic
Stata supports the following logic structures for programming.
Contents
Operators
Arithmetic operators include:
Operator |
Function |
+ |
addition |
- |
subtraction |
* |
multiplication |
/ |
division |
^ |
exponentiation |
unary - or ~ |
negation |
String operators include:
Operator |
Function |
+ |
concatenation |
There is an operator taking one integer argument and one string argument:
Operator |
Function |
* |
duplication of a string |
Relational operators include:
Operator |
Function |
> |
greater than |
>= |
greater than or equal |
< |
less than |
<= |
less than or equal |
== |
equal |
!= or ~= |
not equal |
Relational operators resolve to values of 0 or 1, so they can be mixed with arithmetic operations.
Relational operators cannot be chained, i.e. 1 < 2 < 3 is not valid syntax.
Logical operators include:
Operator |
Function |
& |
and |
| |
or |
! or ~ |
not |
Conditional Processing
Most commands support an if EXPR clause. Reference the command's specific syntax.
replace foo = bar if baz==1
If
A command can be made to operate conditionally in the sense that the command itself may or may not be called.
if ${debug}==1 assert errors==0
if ${debug}==1 {
assert errors==0
}An if structure can be followed by an else structure.
if ${debug}==1 assert errors==0
else display "Not in debug mode"
if ${debug}==1 {
assert errors==0
}
else {
display "Not in debug mode"
}An 'elif'-type structure is only achieved by opening a new if structure on the else structure.
if ${debug}==1 {
assert errors==0
}
else if ${debug}==0 {
display "Not in debug mode"
}
else {
display "Debug in unknown state"
}
By
The -by- prefix command causes a command to be repeated within groups. A common use-case of the by structure is for identifying duplicate cases.
sort foo bar baz by foo bar baz: generate byte duplicate = cond(_N==1, 0, _n)
