0Pricing
R Academy · Lesson

rep() for Repeating Values

Repeat values and vectors with rep(), times, and each arguments.

Introduction to rep()

rep() stands for replicate. It repeats values or vectors a specified number of times. It is one of the most useful tools for creating structured test data, balanced datasets, and filling vectors with default values.

# Repeat a single value
zeros <- rep(0, times = 5)
cat('Five zeros:', zeros, '
')

# Repeat a string
status <- rep('active', times = 4)
cat('Status:', status, '
')

rep(x, times) — Repeat Whole Vector

When x is a vector and times is a single integer, rep() repeats the entire vector that many times. The output length is length(x) * times.

# Repeat a vector 3 times
weekend <- c('Saturday', 'Sunday')
four_weekends <- rep(weekend, times = 4)
cat('4 weekends:', four_weekends, '
')

# Repeat numeric vector
pattern <- c(1, 2, 3)
cat('Pattern x3:', rep(pattern, times = 3), '
')

All lessons in this course

  1. The Colon Operator for Integer Ranges
  2. seq() for Custom Sequences
  3. rep() for Repeating Values
  4. Named Vectors and Named Sequences
← Back to R Academy