0
0
R Programmingprogramming~5 mins

Logical operators (&, |, !, &&, ||) in R Programming

Choose your learning style9 modes available
Introduction

Logical operators help you check if conditions are true or false. They let you combine or change these true/false checks easily.

When you want to check if two things are both true at the same time.
When you want to see if at least one of many things is true.
When you want to reverse a true or false answer.
When you want to test conditions on many items in a list or vector.
When you want to test just the first item in a list or vector for a quick decision.
Syntax
R Programming
x & y   # element-wise AND
x | y   # element-wise OR
!x      # NOT (negation)
x && y  # first element AND
x || y  # first element OR

& and | work on each item in vectors separately.

&& and || only check the first item of each vector.

Examples
Checks each pair of items: TRUE & TRUE = TRUE, FALSE & TRUE = FALSE, TRUE & FALSE = FALSE.
R Programming
c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE)
Checks each pair of items: TRUE | FALSE = TRUE, FALSE | FALSE = FALSE, TRUE | TRUE = TRUE.
R Programming
c(TRUE, FALSE, TRUE) | c(FALSE, FALSE, TRUE)
Reverses each item: TRUE becomes FALSE, FALSE becomes TRUE.
R Programming
!c(TRUE, FALSE, TRUE)
Checks only first items: TRUE && FALSE = FALSE.
R Programming
c(TRUE, FALSE) && c(FALSE, TRUE)
Sample Program

This program shows how each logical operator works on vectors and single elements.

R Programming
a <- c(TRUE, FALSE, TRUE)
b <- c(FALSE, TRUE, TRUE)

# Element-wise AND
print(a & b)

# Element-wise OR
print(a | b)

# Negation
print(!a)

# First element AND
print(a && b)

# First element OR
print(a || b)
OutputSuccess
Important Notes

Use & and | when working with vectors to get results for each item.

Use && and || when you only want to check the first item, often in if statements.

Remember ! flips TRUE to FALSE and FALSE to TRUE.

Summary

Logical operators help combine or change TRUE/FALSE values.

& and | work on every item in vectors.

&& and || check only the first item.