Recycling (R)

Recycling is R's rule for combining vectors of different lengths: the shorter vector is repeated (recycled) to match the longer one's length during element-wise operations.

R

When you do arithmetic or comparison on two vectors of unequal length, R reuses the shorter one from the start until it lines up with the longer. So c(1, 2, 3, 4) + c(10, 20) becomes c(11, 22, 13, 24) — the second vector is recycled to (10, 20, 10, 20). The most common case is a length-1 vector (a 'scalar'), which is why v * 2 multiplies every element.

Recycling is convenient but a frequent source of subtle bugs. If the longer length isn't a multiple of the shorter, R still recycles partially and emits a warning ('longer object length is not a multiple of shorter object length') — a sign your lengths probably don't match by mistake.

Recycling works hand in hand with vectorization. Used intentionally (scalar with vector), it's clean and idiomatic; relied on accidentally between two multi-element vectors, it can produce wrong answers, so check your lengths.

Syntax

c(1, 2, 3, 4) + c(10, 20)   # 10,20 recycled

Examples

R

print(c(1, 2, 3, 4) + c(10, 20))
print(c(1, 2, 3, 4) * 2)

Output:

[1] 11 22 13 24
[1] 2 4 6 8

See also

Back to the Dictionary