R Tutorial



R BOOLEANS


Booleans in R

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.

Creating Boolean Values

You can directly assign logical values to variables like this:

is_sunny <- TRUE
is_raining <- FALSE
  

Boolean Expressions and Comparisons

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)
  

Logical Operators

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

Examples with Logical Operators

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
  

Summary

  • Booleans in R are represented by TRUE and FALSE.
  • They result from comparisons or logical operations.
  • Logical operators include && (AND), || (OR), and ! (NOT).

Practice Exercise

Try the following:

  • Create two variables with numeric values.
  • Use comparison operators to create Boolean expressions.
  • Combine these expressions using logical operators.
  • Print the results.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review