R AND OR Operators

R Tutorial

🔗 R AND ( & , && ) and OR ( | , || ) Operators

(Beginner → Interview Level)

In R, logical operators are used to combine conditions.
The most important ones are AND and OR.


1️⃣ AND Operator in R

The AND operator returns TRUE only if all conditions are TRUE.

Types of AND operators

OperatorNameUse
&Element-wise ANDVectors
&&Short-circuit ANDSingle condition / if

🔹 Example: AND (&) with Vectors


 

Output

[1] TRUE FALSE FALSE

👉 Checks each element.


🔹 Example: AND (&&) with if condition


 

✔ Stops checking as soon as condition becomes FALSE.


2️⃣ OR Operator in R

The OR operator returns TRUE if at least one condition is TRUE.

Types of OR operators

OperatorNameUse
``Element-wise OR
``

🔹 Example: OR (|) with Vectors


 

Output

[1] TRUE FALSE TRUE

🔹 Example: OR (||) with if condition


 


3️⃣ AND / OR with Numeric Conditions

x <- 15

x > 10 & x < 20

Output

[1] TRUE
x < 5 | x > 10

Output

[1] TRUE

4️⃣ AND / OR in if–else Statements


 


5️⃣ Difference Between & vs && and | vs || ⭐ (Very Important)

Feature&&&
TypeElement-wiseShort-circuit
Works onVectorsSingle logical value
Used inCalculationsif / while

| Feature | | | || |
|——|—-|—-|
| Type | Element-wise | Short-circuit |
| Works on | Vectors | Single logical value |

📌 Rule

  • Use & and |vectors

  • Use && and ||if / while


6️⃣ Common Mistakes ❌

❌ Using && with vectors
❌ Using & inside if for multiple values
❌ Forgetting operator precedence


7️⃣ Interview / Exam Questions & Answers ⭐

Q1. What does AND operator do in R?

Answer:
Returns TRUE only when all conditions are TRUE.


Q2. Difference between & and &&?

Answer:

  • & works element-wise on vectors

  • && checks only the first element and is used in conditions


Q3. Difference between | and ||?

Answer:

  • | is vectorized OR

  • || is short-circuit OR for single conditions


Q4. Write a program to check if a number lies between 10 and 50.


 


Q5. What is short-circuit evaluation?

Answer:
R stops evaluating further conditions once the result is known (&&, ||).


✅ Summary

& → AND for vectors
&& → AND for conditions
| → OR for vectors
|| → OR for conditions
✔ Essential for if, loops, filtering data

You may also like...