rep() Function in R (4 Examples)

rep() is a built-in R function that replicates the values in the provided vector. This tutorial shows how to use rep() function in R with 4 examples.

Example 1

The following code is to repeat the number 4 twice.

# repeat the number 4 twice
rep(4, 2)

Output:

[1] 4 4

Example 2

# repeat 4 times of the number from 1 to 3
rep(1:3, 4)

Output:

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

Example 3

You can also add the parameter of length.out to restrict the length of the output. The following is the example.

# add the restriction of length = 5 to the function
rep(1:3, 4, length.out=5)

Output:

[1] 1 2 3 1 2

Example 4

You can also the each parameter in rep() to repeat the elements of x each time.

# add each = 3 to repeat the elements in the X (i.e., 1:2) 
rep(1:2, 4, each=3)

Output:

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