Challenge - 5 Problems
Logical Indexing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of logical indexing with NA values
What is the output of the following R code?
R Programming
x <- c(2, NA, 5, 8, NA) result <- x[!is.na(x) & x > 4] print(result)
Attempts:
2 left
💡 Hint
Remember that logical indexing excludes NA when using !is.na().
✗ Incorrect
The code selects elements of x that are not NA and greater than 4. Only 5 and 8 satisfy both conditions.
❓ Predict Output
intermediate2:00remaining
Logical indexing with multiple conditions
What does this R code print?
R Programming
v <- c(10, 15, 20, 25, 30) subset <- v[v %% 10 == 0 & v > 15] print(subset)
Attempts:
2 left
💡 Hint
Check which numbers are multiples of 10 and greater than 15.
✗ Incorrect
The code selects numbers divisible by 10 and greater than 15. These are 20 and 30.
🔧 Debug
advanced2:00remaining
Identify the error in logical indexing
What error does this R code produce?
R Programming
data <- c(1, 2, 3, 4, 5) index <- c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE) result <- data[index] print(result)
Attempts:
2 left
💡 Hint
Check the length of the logical vector compared to the data vector.
✗ Incorrect
The logical index vector is longer than the data vector, causing the error 'logical subscript too long'.
❓ Predict Output
advanced2:00remaining
Logical indexing with named vectors
What is the output of this R code?
R Programming
scores <- c(John=85, Mary=92, Paul=78, Lisa=90) high_scores <- scores[scores >= 90] print(names(high_scores))
Attempts:
2 left
💡 Hint
Logical indexing keeps names of selected elements.
✗ Incorrect
The code selects scores 90 or above and prints their names, which are Mary and Lisa.
❓ Predict Output
expert2:00remaining
Complex logical indexing with NA and recycling
What is the output of this R code?
R Programming
x <- c(NA, 3, NA, 7, 5) idx <- c(TRUE, FALSE) result <- x[!is.na(x) & idx] print(result)
Attempts:
2 left
💡 Hint
Logical vector idx is recycled to match length of x.
✗ Incorrect
The logical vector idx is recycled to length 5: TRUE, FALSE, TRUE, FALSE, TRUE. Combined with !is.na(x), positions 2, 4 and 5 are not NA. But idx at position 2 is FALSE, position 4 is FALSE, so only position 5 is selected.