R Booleans
Booleans in R are logical values that can either be TRUE
or FALSE
. They are commonly used in conditional statements and logical operations, making them fundamental to decision-making processes in R programming.
Key Topics
1. Boolean Values
In R, TRUE
and FALSE
represent Boolean values. They are case-sensitive and should be written in uppercase.
# Boolean values in R
is_true <- TRUE
is_false <- FALSE
print(is_true)
print(is_false)
Output:
[1] FALSE
Code Explanation: The variables is_true
and is_false
are assigned Boolean values TRUE
and FALSE
, respectively. The print()
function displays these values.
2. Logical Operations
R supports logical operations such as &
(AND), |
(OR), and !
(NOT) to combine or negate Boolean values.
# Logical operations
result_and <- TRUE & FALSE # AND operation
result_or <- TRUE | FALSE # OR operation
result_not <- !TRUE # NOT operation
print(result_and)
print(result_or)
print(result_not)
Output:
[1] TRUE
[1] FALSE
Code Explanation: The &
operator performs a logical AND, resulting in FALSE
because both values are not TRUE
. The |
operator performs a logical OR, resulting in TRUE
because at least one value is TRUE
. The !
operator negates TRUE
, resulting in FALSE
.
3. Comparison Operators
Comparison operators are used to compare values and return a Boolean result: TRUE
or FALSE
. Common comparison operators in R include:
Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
# Using comparison operators
x <- 5
y <- 10
is_equal <- (x == y) # Equal to
is_not_equal <- (x != y) # Not equal to
is_greater <- (x > y) # Greater than
is_less <- (x < y) # Less than
print(is_equal)
print(is_not_equal)
print(is_greater)
print(is_less)
Output:
[1] TRUE
[1] FALSE
[1] TRUE
Code Explanation: The comparison operators compare x
and y
. x == y
returns FALSE
because 5 is not equal to 10. x != y
returns TRUE
because 5 is not equal to 10. x > y
returns FALSE
because 5 is not greater than 10, and x < y
returns TRUE
because 5 is less than 10.
Key Takeaways
- Boolean values in R are
TRUE
andFALSE
(case-sensitive). - Logical operations include AND (
&
), OR (|
), and NOT (!
). - Comparison operators return Boolean values based on the comparison of two values.