How to repeat a vector elements N times each in R
In this tutorial, we are going to learn about how to repeat a vector elements n times each in the R language.
Repeat the vector elements N times
To repeat a vector elements N times each, we can use the built-in rep() function in R language.
The “rep()” function accepts 2 arguments, the first argument is a “vector” and the second argument is the number of times to repeat the each element in the vector.
Here is an example, that repeats the each element in vector n number of times:
prices = c(1, 2, 3)
result = rep(prices, each=2)
print(result)
Output:
[1] 1 1 2 2 3 3
In the example above, we have passed the second arguments each=2
. So that, it repeats the each element in the vector 2 times.
Instead of repeating the each element in the vector n number of times, we can also repeat the whole vector in N number of times.
Here is an example:
prices = c(1, 2, 3)
result = rep(prices, times=3)
print(result)
Output:
[1] 1 2 3 1 2 3 1 2 3