0
0
R Programmingprogramming~20 mins

Switch statement in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple switch statement
What is the output of this R code using switch?
R Programming
result <- switch("b", a = 1, b = 2, c = 3)
print(result)
ANULL
B[1] 2
C[1] 3
D[1] 1
Attempts:
2 left
💡 Hint
Remember that switch matches the first argument to the names.
Predict Output
intermediate
2:00remaining
Switch with numeric index
What will this R code print?
R Programming
result <- switch(3, "apple", "banana", "cherry", "date")
print(result)
A[1] "cherry"
B[1] "banana"
C[1] "apple"
D[1] "date"
Attempts:
2 left
💡 Hint
When the first argument is a number, switch returns the element at that position.
🔧 Debug
advanced
2:00remaining
Error in switch with unnamed arguments
What error does this R code produce?
R Programming
result <- switch("x", "apple", "banana", "cherry")
print(result)
A[1] "apple"
BError in switch: EXPR must be a length 1 vector
CNULL
DError: no matching case found
Attempts:
2 left
💡 Hint
If the first argument is a string but no matching name exists, what does switch return?
Predict Output
advanced
2:00remaining
Switch with expression and default
What is the output of this R code?
R Programming
x <- "z"
result <- switch(x, a = 10, b = 20, c = 30, 40)
print(result)
A[1] 40
B[1] 20
C[1] 30
D[1] 10
Attempts:
2 left
💡 Hint
If no named match is found, switch returns the last unnamed argument as default.
🧠 Conceptual
expert
2:00remaining
Behavior of switch with numeric zero
What happens when you run this R code?
R Programming
result <- switch(0, "apple", "banana", "cherry")
print(result)
A[1] "banana"
B[1] "apple"
C[1] "cherry"
DNULL
Attempts:
2 left
💡 Hint
Check how switch treats numeric indices outside the valid range.