In R, a Boolean (also called logical) is a data type that can have only two possible values: TRUE
or FALSE
.
Booleans are widely used for decision-making, comparisons, and controlling the flow of programs.
You can directly assign logical values to variables like this:
is_sunny <- TRUE is_raining <- FALSE
Booleans often result from comparison operators that compare values:
a <- 10 b <- 20 a == b # FALSE (equal to) a != b # TRUE (not equal to) a > b # FALSE (greater than) a < b # TRUE (less than) a >= 10 # TRUE (greater than or equal to) b <= 20 # TRUE (less than or equal to)
You can combine Boolean values using logical operators:
Operator | Description | Example |
---|---|---|
&& |
Logical AND (TRUE if both TRUE) | TRUE && FALSE # FALSE |
|| |
Logical OR (TRUE if any TRUE) | TRUE || FALSE # TRUE |
! |
Logical NOT (reverses TRUE/FALSE) | !TRUE # FALSE |
x <- 15 y <- 25 # Check if x is between 10 and 20 is_between <- (x > 10) && (x < 20) print(is_between) # TRUE # Check if either x or y is greater than 30 check <- (x > 30) || (y > 30) print(check) # FALSE # Negation example not_true <- !TRUE print(not_true) # FALSE
TRUE
and FALSE
.&&
(AND), ||
(OR), and !
(NOT).Try the following:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!