R Booleans / Logical Values
🔢 R Booleans / Logical Values
In R, Boolean values (also called logical values) represent TRUE or FALSE.
They are the foundation of conditions, filtering, decision-making, and data analysis.
1️⃣ What are Logical Values in R?
R has two logical constants:
📌 They are case-sensitive (TRUE ✔, true ❌).
2️⃣ Creating Logical Values
Logical values are created using comparison operators.
3️⃣ Logical Variables
4️⃣ Logical Vectors ⭐
R supports vectorized logical operations.
📌 Very important for data filtering.
5️⃣ Logical Operators 🔗
Element-wise Logical Operators
| Operator | Meaning |
|---|---|
& |
AND |
|
|
! |
NOT |
Short-circuit Logical Operators ⭐
| Operator | Meaning |
|---|---|
&& |
AND (first element only) |
| ` |
📌 Used mainly in if conditions.
6️⃣ Logical Values in if Statement ⭐
⚠️ if requires a single TRUE/FALSE, not a vector.
7️⃣ Logical Values with which() ⭐
✔ Returns positions of TRUE values.
8️⃣ Logical Values with any() and all() ⭐
any()
Returns TRUE if any value is TRUE.
all()
Returns TRUE if all values are TRUE.
9️⃣ Handling NA in Logical Values ⚠️
📌 Use na.rm = TRUE to ignore NA.
🔟 Logical Values vs Numeric Values
✔ Useful in calculations.
1️⃣1️⃣ Common Mistakes ❌
❌ Using true instead of TRUE
❌ Using vector in if condition
❌ Confusing & and &&
❌ Ignoring NA values
📌 Interview Questions & MCQs (Very Important)
Q1. What are logical values in R?
A) 1 and 0
B) TRUE and FALSE
C) Yes and No
D) T and F
✅ Answer: B
Q2. Are logical values case-sensitive?
A) Yes
B) No
✅ Answer: A
Q3. Difference between & and &&?
A) Both same
B) && works element-wise
C) & works element-wise
D) No difference
✅ Answer: C
Q4. What does any() do?
A) Checks all TRUE
B) Checks any TRUE
C) Counts TRUE
D) Filters data
✅ Answer: B
Q5. Output of as.numeric(TRUE)?
A) 0
B) 1
C) TRUE
D) Error
✅ Answer: B
🔥 Real-Life Use Cases
✔ Filtering datasets
✔ Conditional logic
✔ Decision making
✔ Data validation
✔ Statistical rules
✅ Summary
-
R has TRUE and FALSE
-
Logical values are created via comparisons
-
R supports vectorized logical operations
-
&vs&&is crucial -
Handle
NAcarefully -
Core concept for R programming, exams & data science
