rep

Basics

rep is short for replicate. It accepts an object, x, and up to three additional arguments: times, length.out, and each.

  • times is a non-negative number of repetitions for the whole object x.

  • length.out specifies the end length you want the result to be.

  • each specifies the number of times each element in x will be repeated.

rep will repeat the values in x as many times as it takes to reach the provided length.out.


Examples

How do I repeat values in a vector 3 times?

Click to see solution
vec <- c(1,2,3)
rep(vec, times=3)

# this matches `rep(vec,3)` -- however, we recommend naming arguments to help people who read your code in the future
[1] 1 2 3 1 2 3 1 2 3

How do I repeat the values in a vector until it’s the same length as another vector?

Click to see solution
vec <- c(1,2,3)
other_vec <- c(1,2,2,2,2,2,2,8)
rep(vec, length.out=length(other_vec))
[1] 1 2 3 1 2 3 1 2

When adding vectors in R, the objects must be the same size or one object’s length must be a multiple of the other. If the second option occurs, R utilizes vector recycling, where the tracking of the shorter vector is looped when all its values are exhausted.

Since this does not work when the vectors do not share a multiple, we can use rep to guarantee vector addition, even if we don’t know length.

First, the implication of adding vec to other_vec with no checks:

vec + other_vec
`Warning in vec + other_vec: longer object length is not a multiple of shorter object length`

Not what we want. Now, using rep as we did above, we get the following:

# Left of + matches the code above, both left and right side now have length 8

rep(vec, length.out=length(other_vec)) + other_vec
[1]  2  4  5  3  4  5  3 10

Perfect! Now we know how to use vector recycling when the vectors are not multiples of one another.

How can I repeat each value inside a vector a certain amount of times?

Click to see solution
vec <- c(1,2,3)
rep(vec, each=3)
[1] 1 1 1 2 2 2 3 3 3

How can I repeat the values in one vector based on the values in another vector?

Click to see solution
vec <- c(1,2,3)
rep_by <- c(3,2,1)
rep(vec, times=rep_by)
[1] 1 1 1 2 2 3