R Tutorial

# Logical Operators in R

Logical operators in R are symbols or words used to perform logical operations on values, expressions, or conditions. These operators are vital for making decisions and evaluating expressions that yield either TRUE or FALSE results.

The following are the basic logical operators in R:

1. ==: This operator tests for equality. For example, 10 == 10 returns TRUE.
2. !=: This operator tests for inequality. For example, 10 != 10 returns FALSE.
3. >: This operator tests for greater than. For example, 10 > 5 returns TRUE.
4. <: This operator tests for less than. For example, 10 < 5 returns FALSE.
5. >=: This operator tests for greater than or equal to. For example, 10 >= 5 returns TRUE.
6. <=: This operator tests for less than or equal to. For example, 10 <= 10 returns TRUE.

Here's an elaborate explanation with examples:

## AND Operator (& or &&)

The & operator computes element-wise logical AND between two vectors, whereas the && operator evaluates the first element of each vector and returns a single result.

x <- c(TRUE, FALSE, TRUE) y <- c(FALSE, TRUE, TRUE) result <- x & y # Result: FALSE, FALSE, TRUE

## OR Operator (| or ||)

The operator computes element-wise logical OR between two vectors, whereas the operator evaluates the first element of each vector and returns a single result.

x <- c(TRUE, FALSE, TRUE) y <- c(FALSE, TRUE, TRUE) result <- x y # Result: TRUE, TRUE, TRUE

## NOT Operator (!)

The ! operator is used to negate logical values.

x <- c(TRUE, FALSE, TRUE) result <- !x # Result: FALSE, TRUE, FALSE

## Comparison Operators (==, !=, <, >, <=, >=)

Comparison operators are used to compare values and return logical values.

a <- 5 b <- 10 result1 <- a == b # Equal: FALSE result2 <- a < b # Less than: TRUE

## Combining Operators

Logical operators can be combined to create complex conditions.

age <- 25 income <- 50000 result <- (age >= 18) & (income > 30000) # Both conditions are TRUE

### Conclusion

Logical operators are a powerful tool for controlling the flow of execution of your R code. These logical operators are crucial for evaluating conditions, making decisions, filtering data, and controlling the flow of your R programs. By understanding and utilizing these operators effectively, you can create dynamic and responsive code that adapts to different scenarios and conditions.