The rep
function allows us to repeat R vectors by specifying how many times we want to repeat the whole vector, or how many times we want to repeat each element of the vector.
Repeat a Vector n times
Assume that our vector is the x<-c(1,2,3,4,5)
and we want to repeat it 3 times:
x<-c(1,2,3,4,5) rep(x,times=3)
Output:
[1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Repeat each Vector Element n times
Let’s say that we want to repeat each vector element 3 times:
x<-c(1,2,3,4,5) rep(x,each=3)
Output:
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Note that you can use the length.out
when you want to repeat the vector until you reach a specific number of elements. Finally, there is another trick where you can specify how many times each element will be repeated. For example:
x<-c(1,2,3,4,5) # repeat the first and second element 1 time # the third and forth element 2 times # and the fifth element 3 times rep(x,times=c(1,1,2,2,3))
Output:
[1] 1 2 3 3 4 4 5 5 5