r vector recycling

R Vector Recycling

Posted on

How To Recycling a Vector in R?

R Vector Recycling is a process in which two vectors are involved in an operation, which needs the vectors to have the same length, and R repeats the elements of shorter vector to match the length of longer vector.

Vector Recycling during Addition

An addition operation of two vectors requires the two vectors to have the same length. If a vector is smaller that the other in length, Vector Recycling commits automatically.

Examples:

When we have two vectors: a and ba has length 5, and b is of length 2. We try to add these two vectors. During addition, R implicitly performs Vector Recycling and increases the length of b to 5 by repeating its elements. But, there will be a warning message as shown below.

m <- c(100, 200, 300, 400, 500)
n <- c(2, 5)
result <- m + n
print(result)

#output:
Warning message:
In a + b : longer object length is not a multiple of shorter object length
[1] 102 205 302 405 502

Conclusion:

A Vector recycling is a process that runs automatically in operation of two vectors that requires the two vectors have the same length.