R Logical Data Type
The logical data type stores one of two values: TRUE or FALSE. These values represent yes/no, on/off, and pass/fail conditions. Logical values are the backbone of every decision and filter operation in R.
Creating Logical Variables
is_student <- TRUE has_passed <- FALSE account_active <- TRUE class(is_student) # "logical"
Always write TRUE and FALSE in full uppercase. R does not recognize true or True as logical values.
Logical Values from Comparisons
Most logical values in real R code come from comparison operations, not from typing TRUE or FALSE directly.
score <- 85 score > 80 # TRUE score < 50 # FALSE score == 85 # TRUE (two equals signs = "is equal to") score != 100 # TRUE (not equal) score >= 85 # TRUE (greater than or equal) score <= 60 # FALSE (less than or equal)
Logical Operators
Operator Meaning Example Result ────────────────────────────────────────────────────── & AND TRUE & FALSE FALSE | OR TRUE | FALSE TRUE ! NOT !TRUE FALSE && AND (scalar) (5 > 3) && (2 < 4) TRUE || OR (scalar) (1 > 5) || (3 > 2) TRUE
The single & and | work element-by-element on vectors. The double && and || evaluate only the first element and are used in if statements.
Diagram: AND / OR Truth Table
A B A & B A | B !A ────────────────────────────────────── TRUE TRUE TRUE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE
Using Logical Values to Filter Data
ages <- c(15, 22, 17, 30, 19, 14) # Which ages are 18 or older? is_adult <- ages >= 18 print(is_adult) # [1] FALSE TRUE FALSE TRUE TRUE FALSE # Get only adult ages adults <- ages[is_adult] print(adults) # [1] 22 30 19
This pattern — create a logical vector, then use it to filter — appears constantly in data analysis.
Logical Values in Arithmetic
R treats TRUE as 1 and FALSE as 0 in math operations. This makes counting conditions very easy.
scores <- c(45, 78, 90, 55, 88, 62) passed <- scores >= 60 sum(passed) # 4 — how many passed mean(passed) # 0.6667 — what fraction passed (66.7%)
Checking and Converting Logical
is.logical(TRUE) # TRUE
is.logical(1) # FALSE (1 is numeric, not logical)
as.logical(1) # TRUE
as.logical(0) # FALSE
as.logical("TRUE") # TRUE
as.logical("yes") # NA (R doesn't know "yes" means TRUE)
Common Uses of Logical Data
Use Case Example
─────────────────────────────────────────────────────────────
Filtering rows in a data frame data[data$age > 30, ]
Stopping a loop while (!done) { ... }
Checking for missing values is.na(value)
Testing if a file exists file.exists("data.csv")
Validating user input if (is.numeric(x)) { ... }
Logical values seem simple — just two possibilities — but they control the flow of every significant R program. Mastering how TRUE and FALSE work with comparisons and operators gives you the power to make your code respond intelligently to data conditions.
