R Academy · Lesson

rep() for Repeating Values

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

Lesson 3 of 413 steps

rep() for Repeating Values is a free R Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.

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), '
')

rep(x, each) — Repeat Each Element

The each argument repeats each individual element before moving to the next one. This is the key difference from times: each repeats elements in place.

groups <- c('A', 'B', 'C')

# times: repeats whole vector
cat('times=3:', rep(groups, times = 3), '
')
# A B C A B C A B C

# each: repeats each element before next
cat('each=3 :', rep(groups, each = 3), '
')
# A A A B B B C C C

rep(x, times = c(...)) — Variable Repeats

When times is a vector of the same length as x, each element of x is repeated the corresponding number of times. This gives fine-grained control over repetition.

# Different number of repeats per element
fruits <- c('apple', 'banana', 'cherry')
counts <- c(3, 1, 2)

fruit_basket <- rep(fruits, times = counts)
cat('Fruit basket:', fruit_basket, '
')
# apple apple apple banana cherry cherry

# Useful for creating category labels
cat('Length:', length(fruit_basket), '
')

rep_len() — Repeat to Fixed Length

rep_len(x, length.out) repeats vector x until the result reaches exactly length.out elements. The repetition is cyclic — it wraps around the vector as needed.

# Cycle through seasons to fill 12 months
seasons <- c('Spring', 'Summer', 'Autumn', 'Winter')
year_seasons <- rep_len(seasons, length.out = 12)
cat('12 months by season:', year_seasons, '
')

# Cycle through 1, 2, 3 for 10 items
rotation <- rep_len(1:3, length.out = 10)
cat('Rotation:', rotation, '
')

Combining times and each

You can use times and each together to create more complex repetition patterns. R applies each first (expanding each element), then repeats the resulting vector times times.

# each=2 then times=3
vals <- c(1, 2)
result <- rep(vals, each = 2, times = 3)
cat('each=2, times=3:', result, '
')
# 1 1 2 2  repeated 3 times: 1 1 2 2 1 1 2 2 1 1 2 2

cat('Length:', length(result), '
')

Creating Balanced Group Labels

A classic use of rep() is creating balanced group labels for experiments — where you want an equal number of observations in each group.

# 5 subjects per treatment group
treatments <- c('Control', 'LowDose', 'HighDose')
n_per_group <- 5

group_labels <- rep(treatments, each = n_per_group)
cat('Group labels:', group_labels, '
')
cat('Total subjects:', length(group_labels), '
')

# Count per group
for (g in treatments) {
  cat(g, ':', sum(group_labels == g), '
')
}

Repeating Logical Values

rep() works with any data type, including logical values. This is useful for creating masks, flags, or alternating TRUE/FALSE patterns.

# Alternating TRUE/FALSE pattern
alternate <- rep(c(TRUE, FALSE), times = 5)
cat('Alternating mask:', alternate, '
')

# Apply mask to select every other element
data_vals <- 10:19
cat('Every other value:', data_vals[alternate], '
')

# Create a block pattern: 3 TRUE then 3 FALSE
block <- rep(c(TRUE, FALSE), each = 3)
cat('Block pattern:', block, '
')

rep() for Matrix Filling

You can use rep() to quickly fill matrices with patterned data. Since matrix() accepts a vector as input, combining it with rep() makes pattern matrices easy.

# Fill a 3x4 matrix with a repeating pattern
pattern <- rep(c(1, 0), times = 6)
checker <- matrix(pattern, nrow = 3, ncol = 4)
cat('Checkerboard-like matrix:
')
print(checker)

# Fill diagonal-like with rep
fill <- rep(1:4, each = 3)
cat('Repeated fill:', fill, '
')

Expanding a Summary Table

A practical use of rep() with variable times: converting a frequency table back into a raw data vector. If you know how many times each value occurred, rep() reconstructs the observations.

# Summary: grade frequencies
grades <- c('A', 'B', 'C', 'D')
frequencies <- c(5, 12, 8, 3)

# Reconstruct raw grade vector
raw_grades <- rep(grades, times = frequencies)
cat('Raw grades (', length(raw_grades), 'students):', raw_grades, '
')

# Verify frequency table
cat('Freq table:
')
print(table(raw_grades))

rep() Summary

Here is a quick reference for rep():

  • rep(x, times = n) — repeat entire x n times
  • rep(x, each = n) — repeat each element n times
  • rep(x, times = c(...)) — variable repeats per element
  • rep_len(x, n) — cycle x to reach exactly n elements
  • Works with any type: numeric, character, logical, factor
x <- c(10, 20, 30)
cat('times=2  :', rep(x, times = 2), '
')
cat('each=2   :', rep(x, each = 2), '
')
cat('var times:', rep(x, times = c(1, 2, 3)), '
')
cat('rep_len  :', rep_len(x, 7), '
')

Quick Check

What does rep(c(1, 2), each = 3) produce?

Recap: rep() for Repeating Values

Excellent! Key takeaways from this lesson:

  • rep(x, times) repeats the whole vector; rep(x, each) repeats each element individually
  • Passing a vector to times gives variable repetition counts per element
  • rep_len(x, n) cycles x until exactly n elements are produced
  • Common uses: balanced group labels, masks, frequency table expansion, pattern matrices
  • Works identically with numeric, character, and logical data types
# Create a balanced experiment design
treatments <- c('Placebo', 'Drug_A', 'Drug_B')
subjects_per <- 4

design <- rep(treatments, each = subjects_per)
cat('Experiment design:
')
cat(design, '
')
cat('Total N:', length(design), '
')
Free to start

Learn R with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
43
Lessons
159

Frequently Asked Questions

Is the “rep() for Repeating Values” lesson free?

Yes — any 3 lessons of the R Academy learning path, including “rep() for Repeating Values”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.

What will I learn in “rep() for Repeating Values”?

Repeat values and vectors with rep(), times, and each arguments. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “rep() for Repeating Values” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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