Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Data Management

Conditions and Logical Operators

Select observations in Stata with if and in, combine conditions with & | !, use inlist, inrange and missing(), understand operator precedence and the if/else programming forms.

Selecting the right observations is the core of data work: only adults, only 2015 to 2020, everyone except the control group. Stata does this with if and in qualifiers and a small set of logical operators. This lesson covers them in detail, including operator precedence (where most bugs hide), string conditions and the programming if that is different from the qualifier.

Relational operators

Operator Meaning Example
== equal if sex == 1
!= or ~= not equal if region != "North"
> < greater, less if income > 5000
>= <= greater or equal, less or equal if age >= 18

Strings are written in double quotes: if country == "Peru". Comparisons with strings are case-sensitive, so "peru" is a different value. Use lower(country) == "peru" to ignore case.

Logical operators

Operator Meaning
& and
| or
! or ~ not
STATA
summarize income if age >= 18 & age <= 65
summarize income if region == "North" | region == "South"
summarize income if !(sex == 1)
count if sex == 1 & !missing(income)

A condition on both sides of & must be a complete expression: if age >= 18 & <= 65 is wrong; write age >= 18 & age <= 65.

Operator precedence

When operators mix, Stata evaluates in a fixed order, from highest to lowest: !, then comparison operators, then &, then |. So & binds tighter than |:

STATA
list if region == "North" | region == "South" & age > 60

means North (any age) or (South and age over 60). If you meant "North or South, who are over 60", write it with parentheses:

STATA
list if (region == "North" | region == "South") & age > 60

Always use parentheses when you mix & and |. They cost nothing and make the code readable.

flowchart TD
    A["Condition: A | B & C"] --> B["B & C first"]
    B --> C["then A | (result)"]
    D["Condition: (A | B) & C"] --> E["A | B first"]
    E --> F["then (result) & C"]

Parentheses change which operator runs first.

Handy functions for conditions

STATA
inlist(region_code, 1, 3, 5)         // true if the value is any listed value
inrange(age, 18, 65)                 // true if 18 <= age <= 65 (inclusive)
missing(income)                      // true for ., .a-.z or ""
mi(income)                           // short for missing()
strpos(name, "son") > 0              // text contains "son"
regexm(name, "^A")                   // regular expression: name starts with A

inlist() and inrange() are shorter and less error-prone than a chain of == and |. inrange() is also safe with missing values: a missing value is never inside the range, whereas age >= 18 alone would include missing ages.

The if qualifier and the in qualifier

STATA
list make price if price > 15000        // rows where the condition is true
summarize mpg in 1/20                   // rows 1 to 20 by position
list in -5/l                            // last five rows
tabulate rep78 if foreign == 1, missing

in depends on the current sort order, so results change after sort. if depends only on the data. When you need "the first 10 observations of a sorted group", combine sort with in, or better, create a rank with by (see the next lessons).

Both qualifiers can appear together: list if price > 10000 in 1/50. Observations must satisfy both.

Conditions in generate and replace

The qualifier works in every data-changing command:

STATA
replace income = . if income > 999990
generate hi_income = 1 if income > 80000 & !missing(income)
replace hi_income = 0 if income <= 80000
drop if inlist(country, "Test", "Demo")

Note: generate hi_income = 1 if ... leaves all other observations missing. A flat condition generate hi_income = (income > 80000) gives 0 or 1 for everyone, with the missing-value trap described earlier.

The programming if is different

The qualifier if filters observations. The programming if command, used in do-files, decides whether a block of code runs at all, based on a single value:

STATA
if "`c(os)'" == "Windows" {
    display "Running on Windows"
} else {
    display "Running elsewhere"
}

scalar threshold = 100
if _N > scalar(threshold) {
    display "A large dataset"
}

Here _N is the number of observations. Put else on the same line as the closing brace (} else {). This programming if evaluates one true/false value, not one value per observation. Mixing the two up (using if x > 5 { on a variable) tests only the first observation. We return to this in the programming chapter.

Common mistakes

  1. Using = instead of == in a condition: if sex = 1 is a syntax error.
  2. Forgetting quotes on strings: if region == North looks for a variable named North.
  3. Forgetting missing values with >: covered in the missing-values lesson.
  4. Mixing & and | without parentheses.
  5. Writing if 18 <= age <= 65: chained comparisons are not allowed; use inrange().

Stand-in: evaluate conditions row by row

This model keeps a table, applies conditions written as Python lambdas, and shows the effect of precedence.

Python Stand-in: precedence of & and |

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: inlist and inrange

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which operator has higher precedence in Stata, & or |?

    & is evaluated before |, so use parentheses when mixing them.
  2. 2. Which condition selects ages 18 to 65 inclusive?

    inrange() does it; chained comparisons are not allowed and in selects by row number.
  3. 3. Which of these selects rows by their position in the data?

    in 1/10 means rows 1 through 10 in the current sort order.
  4. 4. What is wrong with list if region == North?

    Without quotes, Stata looks for a variable called North.

Summary

  • Compare with == != > < >= <=; combine with &, | and !; strings need double quotes.
  • & binds tighter than |: add parentheses whenever you mix them.
  • inlist(), inrange() and missing() are shorter and safer than long chains.
  • if selects by condition and in by position (which depends on sort order).
  • The programming if { } block runs code once, based on one value; it is not the same as the qualifier.

Next: Sorting and the by Prefix