Vector Recycling
R Vector Recycling is a process in which two vectors are involved in an operation, that operation needs the vectors to be of same length, and R repeats the elements of shorter vector to match the length of longer vector.
Example
Vector Recycling during Addition
Vector Addition requires the two vectors to be of same length. If a vector is smaller that the other in length, Vector Recycling happens automatically.
In the following program, we have two vectors: a
and b
. a
is of 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.
Example.R
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3)
result <- a + b
print(result)
b
becomes c(1,2,1,3,2)
to match the size of a
.
Output
[1] 11 23 31 43 51
Of course, there would be a warning message after output, as shown in the following.
Warning message:
In a + b : longer object length is not a multiple of shorter object length
Conclusion
In this R Tutorial, we learned what Vector Recycling is in R, with examples.