Skip to content
Related Articles

Related Articles

Improve Article

Replicate elements of vector in R programming – rep() Method

  • Last Updated : 10 Aug, 2021

In the R programming language, A very useful function for creating a vector by repeating a given number/vector with the specified number of times is the rep().

The general structure of rep() : rep(v1,n1).

Here, v1 is repeated n1 times.
 

The forms of rep() functions :

  • rep(v1, times=)
  • rep(v1, each=)
  • rep(v1, length=)

Example 1:



Python3




# Replicate '0' 5 time
rep(0, 5)

Output:

[1] 0 0 0 0 0

Example 2:
rep(v1,  times=)

Python3




# 1,2,3 repeated 3 times in sequencially
rep(1:3,times=3)

Output:

[1] 1 2 3 1 2 3 1 2 3

Example 3:

rep(v1,  each=)

Python3




# 1,2,3 repeated 3 times
rep(1:3,each=3)
Output
[1] 1 1 1 2 2 2 3 3 3

Example 4:

rep(v1,  length=)

Python3




# generate a vector 1,2,3
x<-1:3
# vector x is replicated such that the length is five.
rep(x, length=5)
Output
[1] 1 2 3 1 2

Example 5:

Python3




# 1 is replicated 2 times, and so on
rep(x,c(2,1,3))
Output
[1] 1 1 2 3 3 3



My Personal Notes arrow_drop_up
Recommended Articles
Page :