Hint: Repeat shorter vector to match length, then add [OK]
Common Mistakes:
Adding only first two elements and ignoring recycling
Expecting error due to different lengths
Misaligning recycled elements
4. Consider this R code:
x <- c(5, 10, 15)
y <- c(2, 4, 6, 8)
z <- x + y
What is the problem and how to fix it?
medium
A. Lengths differ and 3 does not divide 4; fix by making lengths compatible.
B. No problem; code runs fine with recycling.
C. Syntax error due to missing parentheses; add parentheses.
D. Vectors must be same length; truncate longer vector.
Solution
Step 1: Check vector lengths
x length is 3, y length is 4.
Step 2: Understand recycling warning
3 does not divide 4 evenly, so R will recycle x but give a warning about length mismatch.
Step 3: Fix the problem
Make vector lengths compatible, e.g., use length 6 or 12, or truncate longer vector.
Final Answer:
Lengths differ and 3 does not divide 4; fix by making lengths compatible. -> Option A
Quick Check:
Unequal lengths without exact multiple cause warnings [OK]
Hint: Lengths must be multiples to avoid warnings [OK]
Common Mistakes:
Ignoring recycling warning
Assuming code runs without warnings
Trying to fix with syntax changes
5. You have two vectors:
v1 <- c(3, 6, 9, 12, 15)
v2 <- c(1, 2)
You want to multiply them element-wise without warnings and get a vector of length 7 by repeating both vectors appropriately. Which code achieves this?
hard
A. rep(v1, each=2) * rep(v2, times=5)
B. v1 * v2
C. v1 + v2
D. rep(v1, length.out=7) * rep(v2, length.out=7)
Solution
Step 1: Understand desired output length
You want a length 7 vector, so both vectors must be length 7.
Step 2: Use rep() with length.out
Using rep(v1, length.out=7) repeats v1 to length 7; similarly for v2.
Step 3: Multiply element-wise
Multiplying these repeated vectors gives length 7 without warnings.
Final Answer:
rep(v1, length.out=7) * rep(v2, length.out=7) -> Option D
Quick Check:
Repeat vectors to same length before operation [OK]
Hint: Use rep() with length.out to match lengths [OK]
Common Mistakes:
Using direct multiplication causing warnings
Using rep() with each or times incorrectly
Adding vectors instead of multiplying
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.