Challenge - 5 Problems
Ifelse Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of ifelse with numeric vector
What is the output of the following R code using
ifelse?R Programming
x <- c(2, 5, 8, 1) result <- ifelse(x > 4, x * 2, x + 1) print(result)
Attempts:
2 left
💡 Hint
Remember that ifelse applies the condition element-wise and returns a vector.
✗ Incorrect
The condition x > 4 is checked for each element: for 2 and 1 it is FALSE, so we add 1; for 5 and 8 it is TRUE, so we multiply by 2.
🧠 Conceptual
intermediate2:00remaining
Understanding ifelse with NA values
What will be the output of this R code using
ifelse with NA values?R Programming
x <- c(NA, 3, 7, NA) result <- ifelse(is.na(x), 0, x) print(result)
Attempts:
2 left
💡 Hint
Check how
is.na(x) returns TRUE or FALSE for each element.✗ Incorrect
The is.na(x) returns TRUE for NA elements, so ifelse replaces those with 0, and keeps other values as is.
🔧 Debug
advanced2:00remaining
Identify the error in ifelse usage
What error does the following R code produce?
R Programming
x <- c(1, 2, 3) result <- ifelse(x > 2, "High", 0) print(result)
Attempts:
2 left
💡 Hint
Check how R handles mixed types in ifelse output vectors.
✗ Incorrect
R coerces numeric 0 to character "0" because the other output is a character string. So no error occurs, and output is character vector.
📝 Syntax
advanced2:00remaining
Syntax error in ifelse usage
Which option contains a syntax error in using
ifelse in R?Attempts:
2 left
💡 Hint
Look for missing commas or parentheses.
✗ Incorrect
Option B is missing a comma between the condition and the true value, causing a syntax error.
🚀 Application
expert3:00remaining
Using ifelse to categorize numeric vector
Given
scores <- c(45, 67, 89, 55, 72), which code correctly assigns grades: "Fail" for scores below 50, "Pass" for 50 to 75, and "Distinction" for above 75?R Programming
scores <- c(45, 67, 89, 55, 72)
Attempts:
2 left
💡 Hint
Think about the order of conditions and inclusive ranges.
✗ Incorrect
Option D correctly nests ifelse to assign "Fail" if below 50, then "Pass" if 50 to 75 inclusive, else "Distinction".