Predictive Hacks

How to Repeat Vectors in R

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:



[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:



[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:


# repeat the first and second element 1 time
# the third and forth element 2 times
# and the fifth element 3 times


[1] 1 2 3 3 4 4 5 5 5

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s