You can use the rep() function in R to replicate elements of vectors or lists a certain number of times.
This function uses the following basic syntax:
rep(x, times = 1, length.out = NA, each = 1)
where:
- x: The object to replicate
- times: The number of times to replicate object
- length.out: Repeated x as many times as necessary to create vector of this length
- each: Number of times to replicate individual elements in object
The following examples show how to use this function in practice.
Note: The rep() function is different than the replicate() function.
Example 1: Replicate a Vector Multiple Times
The following code shows how to use the rep() function to replicate a vector three times:
#define vector x #replicate the vector three times rep(x, times=3) [1] 1 10 50 1 10 50 1 10 50
The entire vector was replicated three times.
Example 2: Replicate Each Value in Vector the Same Number of Times
The following code shows how to use the rep() function to replicate each value in the vector five times:
#define vector x #replicate each value in vector five times rep(x, each=5) [1] 1 1 1 1 1 10 10 10 10 10 50 50 50 50 50
Each individual value in the vector was replicated five times.
Example 3: Replicate Each Value in Vector a Different Number of Times
The following code shows how to use the rep() function to replicate each value in the vector a specific number of times:
#define vector
x #replicate each value in vector a specific number of times
rep(x, times=c(2, 5, 3))
[1] 1 1 10 10 10 10 10 50 50 50
From the output we can see:
- The value 1 was replicated 2 times.
- The value 10 was replicated 5 times.
- The value 50 was replicated 3 times.
Example 4: Replicate Each Value in Vector the Same Number of Times, Multiple Times
The following code shows how to use the rep() function to replicate each value in the vector four times and to repeat this process two times:
#define vector x #replicate each value in vector four times and do this process two times rep(x, each=4, times=2) [1] "A" "A" "A" "A" "B" "B" "B" "B" "A" "A" "A" "A" "B" "B" "B" "B"
Each value in the vector was replicated four times and we repeated this process two times.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use the replace() Function in R
How to Use split() Function in R
How to Use the View() Function in R