Challenge - 5 Problems
Vector Recycling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of vector recycling in addition
What is the output of this R code?
c(1, 2, 3, 4) + c(10, 20)
R Programming
c(1, 2, 3, 4) + c(10, 20)
Attempts:
2 left
💡 Hint
Remember that R recycles the shorter vector to match the length of the longer one.
✗ Incorrect
The shorter vector c(10, 20) is repeated to become c(10, 20, 10, 20). Then element-wise addition happens: 1+10=11, 2+20=22, 3+10=13, 4+20=24.
❓ Predict Output
intermediate2:00remaining
Output of vector recycling with logical vectors
What is the output of this R code?
c(TRUE, FALSE, TRUE) & c(FALSE, TRUE)
R Programming
c(TRUE, FALSE, TRUE) & c(FALSE, TRUE)
Attempts:
2 left
💡 Hint
The shorter vector is recycled to match the longer vector length before element-wise AND.
✗ Incorrect
The shorter vector c(FALSE, TRUE) is recycled to c(FALSE, TRUE, FALSE). Then element-wise AND: TRUE & FALSE = FALSE, FALSE & TRUE = FALSE, TRUE & FALSE = FALSE.
🔧 Debug
advanced2:00remaining
Error caused by vector recycling with incompatible lengths
What error does this R code produce?
c(1, 2, 3) + c(10, 20, 30, 40)
R Programming
c(1, 2, 3) + c(10, 20, 30, 40)
Attempts:
2 left
💡 Hint
R recycles shorter vectors but warns if lengths are not multiples.
✗ Incorrect
The shorter vector length 3 does not divide the longer vector length 4 evenly. R recycles but gives a warning about length mismatch.
🧠 Conceptual
advanced2:00remaining
Understanding recycling with named vectors
Given these named vectors in R:
What is the output of
a <- c(x=1, y=2, z=3)
b <- c(y=10, z=20)
What is the output of
a + b?R Programming
a <- c(x=1, y=2, z=3) b <- c(y=10, z=20) a + b
Attempts:
2 left
💡 Hint
Named vectors do not recycle by matching names in arithmetic operations.
✗ Incorrect
R ignores names in arithmetic and recycles by position. b is shorter, so recycled to length 3: c(10, 20, 10). Then addition: 1+10=11, 2+20=22, 3+10=13. But since lengths differ and names exist, a warning is issued and names are dropped, resulting in numeric vector without names.
❓ Predict Output
expert2:00remaining
Output length after recycling with complex vectors
What is the length of the vector produced by this R code?
length(c(1, 2, 3, 4, 5) + c(10, 20))
R Programming
length(c(1, 2, 3, 4, 5) + c(10, 20))
Attempts:
2 left
💡 Hint
The result length matches the longer vector length after recycling.
✗ Incorrect
The shorter vector c(10, 20) is recycled to length 5: c(10, 20, 10, 20, 10). The addition produces a vector of length 5.