rep()

rep(x, times = 1, length.out = NA, each = 1)
Returns: vector · Updated March 13, 2026 · Base Functions
replication vectors base

The rep() function replicates the elements of a vector a specified number of times. It is fundamental for creating repeated patterns, expanding datasets, and constructing test data in R.

Syntax

rep(x, times = 1, length.out = NA, each = 1)

Parameters

ParameterTypeDefaultDescription
xvector or listThe object to replicate
timesinteger1Number of times to repeat the entire vector
length.outintegerNADesired length of the output vector
eachinteger1Number of times to repeat each element individually

Examples

Basic usage

# Repeat the entire vector 3 times
rep(c("a", "b"), times = 3)
# [1] "a" "b" "a" "b" "a" "b"

# Repeat each element 2 times
rep(c("a", "b"), each = 2)
# [1] "a" "a" "b" "b"

Using length.out

# Specify exact output length (truncates or recycles)
rep(1:3, length.out = 7)
# [1] 1 2 3 1 2 3 1

# Useful for creating equal-length vectors
rep(c("train", "test"), each = 50, length.out = 100)
# Creates 100 labels: 50 train, 50 test

Combining times and each

# Both parameters together
rep(1:2, times = 2, each = 3)
# [1] 1 1 1 2 2 2 1 1 1 2 2 2

Common Patterns

Creating indicator variables

groups <- rep(c("control", "treatment"), each = 10)
# Creates 20-group assignment vector

Expanding data for simulation

set.seed(42)
values <- rnorm(5)
repeated <- rep(values, each = 100)
# Each original value repeated 100 times for bootstrap-style analysis

Cycling with length.out

# Alternate pattern for stratified sampling
idx <- rep(1:3, length.out = 90)
table(idx)
# idx
#  1  2  3 
# 30 30 30

See Also