Stats

32 Contributors: 2 Thursday, August 25, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Recycling

Remarks

What is recycling in R

Recycling is when an object is automatically extended in certain operations to match the length of another, longer object.

For example, the vectorised addition results in the following:

c(1,2,3) + c(1,2,3,4,5,6)  
[1] 2 4 6 5 7 9

Because of the recycling, the operation that actually happened was:

c(1,2,3,1,2,3) + c(1,2,3,4,5,6)

In cases where the longer object is not a multiple of the shorter one, a warning message is presented:

c(1,2,3) + c(1,2,3,4,5,6,7)
[1] 2 4 6 5 7 9 8
Warning message:
In c(1, 2, 3) + c(1, 2, 3, 4, 5, 6, 7) :
  longer object length is not a multiple of shorter object length

Another example of recycling:

matrix(nrow =5, ncol = 2, 1:5 )
     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    4    4
[5,]    5    5

Related Examples