What is vector recycling in R?

If we try to perform some operation on two R vectors with different lengths, the R interpreter detects under the hood the shorter one, recycles its items in the same order until the lengths of the two vectors match, and only then performs the necessary operation on these vectors. Before starting vector recycling, though, the R interpreter throws a warning message about the initial mismatch of the vectors’ lengths.

For example, if we try to run the following addition:

c(1, 2, 3, 4, 5) + c(1, 2, 3)Powered By 

The second vector, due to the vector recycling, will actually be converted into c(1, 2, 3, 1, 2). Hence, the final result of this operation will be c(2, 4, 6, 5, 7).

While sometimes vector recycling can be beneficial (e.g., when we expect the cyclicity of values in the vectors), more often, it’s inappropriate and misleading. Hence, we should be careful and mind the vectors’ lengths before performing operations on them.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *