0
0
R Programmingprogramming~5 mins

Vector recycling behavior in R Programming

Choose your learning style9 modes available
Introduction

Vector recycling helps R work with vectors of different lengths by repeating the shorter one to match the longer one. This makes calculations easier and faster.

Adding two vectors of different lengths in a calculation.
Applying a function to vectors where one is shorter than the other.
Combining data where some values repeat to fill missing spots.
Syntax
R Programming
result <- vector1 + vector2

If vectors have different lengths, R repeats the shorter vector until it matches the longer one.

If the longer vector's length is not a multiple of the shorter one, R gives a warning.

Examples
Both vectors have the same length, so addition happens element-wise.
R Programming
c(1, 2, 3) + c(10, 20, 30)
The shorter vector c(10, 20) is repeated to c(10, 20, 10) before addition.
R Programming
c(1, 2, 3) + c(10, 20)
The shorter vector c(10, 20) is repeated twice to match length 4: c(10, 20, 10, 20).
R Programming
c(1, 2, 3, 4) + c(10, 20)
Sample Program

This program adds two vectors of different lengths. The shorter vector v2 is repeated to match v1's length before addition.

R Programming
v1 <- c(5, 10, 15, 20)
v2 <- c(1, 2)
result <- v1 + v2
print(result)
OutputSuccess
Important Notes

Vector recycling only works when the longer vector's length is a multiple of the shorter one; otherwise, R shows a warning.

Recycling helps avoid writing loops for simple repeated operations.

Summary

Vector recycling repeats shorter vectors to match longer ones in operations.

This makes element-wise operations easier and faster in R.

Be careful when lengths don't match perfectly; R will warn you.