What is Vector Recycling in R ?

  R Interview Questions

Operations on vectors need to happen on vectors of the same size. Say, you add

> cats
 John  Ajay Aishu 
    1     2     1 
> dogs
 John  Ajay Aishu  Mary Emily  Siva 
    0     1     2     0     2     1 
> pets = cats + dogs
> pets
 John  Ajay Aishu  Mary Emily  Siva 
    1     3     3     1     4     2

As you can see, the elements in the cats vector are recycled to be equal to the size of the dogs vector in order to do the addition. Since R needs the vectors to be of the same length to perform operations on them, it is auto-adjusting the length by recycling the existing elements. In fact, this is what is happening when you perform operations on vectors with a single number

> avg = pets-mean(pets)
> avg
      John       Ajay      Aishu       Mary      Emily       Siva 
-1.3333333  0.6666667  0.6666667 -1.3333333  1.6666667 -0.3333333

Although the mean(pets) looks like a single numeric number, you should know by now that it is represented internally as a vector in R

> mean(pets)
[1] 2.333333
> class(mean(pets))
[1] "numeric"

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.