rep

rep is short for replicate.

rep accepts an object, x, and up to three additional arguments: times, length.out, and each. times is the number of non-negative times to repeat the whole object x. length.out specifies the end length you want the result to be. each repeats each element in x the number of times specified by each.

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, 3)
[1] 1 2 3 1 2 3 1 2 3
# or

rep(vec, times=3)
[1] 1 2 3 1 2 3 1 2 3

How do I repeat the values in a vector enough times to be 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
# Note that if the end goal is to do something
# like add the two vectors, this can be done
# using vector recycling, where a short vector
# is used to create a longer vector.
rep(vec, length.out=length(other_vec)) + other_vec
[1]  2  4  5  3  4  5  3 10
vec + other_vec
## Warning in vec + other_vec: longer object length is not a multiple of shorter
## object length
[1]  2  4  5  3  4  5  3 10

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