How to Use rep() Function in R: Syntax and Examples
In R, use the
rep() function to repeat elements of a vector. You can specify how many times to repeat each element or the entire vector using arguments like times or each. This helps create repeated sequences easily.Syntax
The rep() function repeats elements of vectors. Its main arguments are:
- x: the vector to repeat
- times: how many times to repeat the whole vector or each element
- each: how many times to repeat each element individually
- length.out: total length of the output vector
r
rep(x, times = 1, each = 1, length.out = NA)
Example
This example shows how to repeat the vector c(1, 2, 3) in different ways using rep().
r
vec <- c(1, 2, 3) # Repeat whole vector 2 times rep(vec, times = 2) # Repeat each element 3 times rep(vec, each = 3) # Repeat with total length 7 rep(vec, length.out = 7)
Output
[1] 1 2 3 1 2 3
[1] 1 1 1 2 2 2 3 3 3
[1] 1 2 3 1 2 3 1
Common Pitfalls
Common mistakes include confusing times and each, or expecting rep() to recycle elements automatically without specifying length.out. Also, using times with a vector instead of a single number can cause unexpected results.
r
vec <- c(4, 5) # Wrong: times as vector (repeats elements differently) rep(vec, times = c(2, 3)) # Right: times as single number (repeat whole vector) rep(vec, times = 3) # Wrong: expecting automatic length rep(vec, times = 2) # length 4, not 5 # Right: specify length.out for exact length rep(vec, length.out = 5)
Output
[1] 4 4 5 5 5
[1] 4 5 4 5 4 5
[1] 4 5 4 5
[1] 4 5 4 5 4
Quick Reference
| Argument | Description |
|---|---|
| x | Vector to repeat |
| times | Number of times to repeat the whole vector or each element |
| each | Number of times to repeat each element |
| length.out | Desired length of the output vector |
Key Takeaways
Use rep(x, times) to repeat the entire vector x multiple times.
Use rep(x, each) to repeat each element of x multiple times individually.
Specify length.out to get an output vector of exact length.
Avoid passing a vector to times unless you want element-wise repetition counts.
rep() is useful for creating repeated sequences quickly and clearly.