rguides

How to Repeat Values in R with rep()

Use rep() to repeat values in R. It covers four common cases: repeating a single value, cycling through a vector, repeating each element in place, and filling to a fixed length. These patterns show up in experiment design, loop initialization, and synthetic data generation.

# Repeat single value 5 times
rep(1, times = 5)

# Repeat vector 3 times (cycles through)
rep(c("a", "b"), times = 3)

# Repeat each element individually (keeps order)
rep(1:3, each = 2)

# Force exact output length
rep(1:2, length.out = 7)

# Create group labels for experiments
rep(c("control", "treatment"), each = 10)

The key distinction is between times (how many full repetitions of the whole vector) and each (how many times to repeat each element before moving to the next). Use length.out when you need a precise vector length regardless of how the input divides. For initializing vectors of zeros or NAs before a loop, rep(NA_real_, 100) is cleaner than typing each element. Use seq() when you need a numeric range with a consistent step instead of copies. rep_len() is a faster variant of rep(x, length.out = n) for simple cycling. For large vectors, pre‑allocating with vector() and filling in a loop is faster than growing with rep().

# Initialize vectors for a loop
x <- rep(NA_real_, 100)
labels <- rep(c("A", "B", "C"), each = 30)

See also

  • rep(), Repeat elements of a vector
  • seq(), Generate regular sequences
  • c(), Combine values into a vector