rep() function in R repeats the specified object a specified number of times. It is used to create a vector with a specified number of entries. It generates a sequence of numbers ensures that a list has the same number of items in each iteration. In this guide, we will look at how to use the rep() function in R with a simple example.
Syntax
rep(x, times, each, length.out)
Arguments
- x represents an expression and can be of any type of data, like a string, number, or vector.
- n represents the number of replications that should be carried out on the first argument. By default, it is considered as 1.
- each represents a non-negative integer. It specifies the number of replications that should be carried out on each element of the vector. By default, it is considered as 1.
- length.out =representsnon-negative integer. It specifies the length of the returned vector. By default, it is NA.
Example 1: Using rep() to Create Vectors
The example below will create a vector length of 8 with the numbers 1, 2, 3, 4, 5, 6, 7, and 8.
#creating a vector of range 1 to 8
x<- rep(1:8,1)
x
Output
[1] 1 2 3 4 5 6 7 8
Example 2: Using rep() to Replicate Vectors
#creates a vector with 1 and 2
x<- c(1,2)
#replicates x 2 times
rep(x, 2)
#replicates x 10 times
rep(x, 10)
Output
[1] 1 2 1 2
[1] 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
Example 3: Using rep() to Create Arrays
rep() can be used to create arrays with consecutive values:
#creating arrays
array1 <- rep(1, 3) #list now has three elements 1, 1, 1
array2 <- rep(1, 5) #list now has five elements 1, 1, 1, 1, 1
#printing arrays
array1
array2
Output
[1] 1 1 1
[1] 1 1 1 1 1
Example 4: Using rep() with the Each Parameter
In this example, we specify that each vector element should repeat three times.
#creating a vector
x <- rep(1:5, each=3)
#printing vector
x
Output
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Example 5: Using rep() with the Length.out Parameter
In this example, we are restricting the length of the vector using the Length.out parameter.
#creating a vector
x <- rep(1:50,length.out=10)
#printing vector
x
Output
[1] 1 2 3 4 5 6 7 8 9 10