R AND OR Operators

🔗 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
| Operator | Name | Use |
|---|---|---|
& | Element-wise AND | Vectors |
&& | Short-circuit AND | Single condition / if |
🔹 Example: AND (&) with Vectors
Output
👉 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
| Operator | Name | Use |
|---|---|---|
| ` | ` | Element-wise OR |
| ` | ` |
🔹 Example: OR (|) with Vectors
Output
🔹 Example: OR (||) with if condition
3️⃣ AND / OR with Numeric Conditions
Output
Output
4️⃣ AND / OR in if–else Statements
5️⃣ Difference Between & vs && and | vs || ⭐ (Very Important)
| Feature | & | && |
|---|---|---|
| Type | Element-wise | Short-circuit |
| Works on | Vectors | Single logical value |
| Used in | Calculations | if / while |
| Feature | | | || |
|——|—-|—-|
| Type | Element-wise | Short-circuit |
| Works on | Vectors | Single logical value |
📌 Rule
Use
&and|→ vectorsUse
&&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
