seq() for Custom Sequences
Control step size, length, and direction with seq().
seq() for Custom Sequences is a free R Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction to seq()
seq() is the flexible sequence generator in R. While : creates integer ranges with step 1, seq() lets you control the start, end, step size, and total length of any numeric sequence.
# Basic seq() usage
basic <- seq(1, 10)
cat('seq(1, 10):', basic, '
')
# With step size
by_two <- seq(0, 20, by = 2)
cat('seq(0, 20, by=2):', by_two, '
')seq(from, to, by) — Custom Step
The by argument sets the step size between consecutive values. It can be any positive or negative number, including decimals. This is useful for generating evenly spaced values at non-integer intervals.
# Decimal step
celsius <- seq(0, 100, by = 12.5)
cat('Every 12.5 degrees:', celsius, '
')
# Step of 0.1
fine_scale <- seq(1.0, 1.5, by = 0.1)
cat('Fine scale:', fine_scale, '
')
# Negative step (descending)
countdown <- seq(10, 0, by = -2)
cat('Countdown by 2:', countdown, '
')seq(from, to, length.out) — Fixed Count
When you know how many values you want rather than the step size, use length.out. R will calculate the step automatically to evenly divide the interval.
# 5 evenly spaced points between 0 and 1
unit_interval <- seq(0, 1, length.out = 5)
cat('5 points in [0,1]:', unit_interval, '
')
# 7 breakpoints for a histogram
breakpoints <- seq(0, 100, length.out = 7)
cat('Histogram breaks:', breakpoints, '
')
# Step is automatically calculated
step <- (100 - 0) / (7 - 1)
cat('Step size:', step, '
')seq(along.with = x) — Match a Vector
seq(along.with = x) generates the integer sequence 1:length(x), identical to seq_along(x). It is useful when you want to pair an index sequence with an existing vector.
rainfall <- c(55.2, 62.1, 48.7, 71.3, 38.9, 90.4, 45.0)
# Generate matching index sequence
idx <- seq(along.with = rainfall)
cat('Indices:', idx, '
')
cat('Rainfall:', rainfall, '
')
# Use to find position of max
cat('Position of max rainfall:', which.max(rainfall), '
')
cat('Max rainfall:', max(rainfall), 'mm
')seq_len(n) — Safe 1 to n
seq_len(n) is equivalent to seq(1, n) or 1:n, but handles the edge case where n = 0 correctly by returning an empty integer vector instead of c(1, 0).
# Normal use
cat('seq_len(5):', seq_len(5), '
')
# Edge case: n = 0
cat('1:0 :', 1:0, '
') # produces 1 0 (WRONG)
cat('seq_len(0):', seq_len(0), '
') # produces integer(0) (CORRECT)
# In practice: safe loop
my_data <- c() # intentionally empty
for (i in seq_len(length(my_data))) {
cat('Processing item', i, '
')
}
cat('Loop completed without error
')Negative Steps with seq()
Setting a negative by value creates a descending sequence. The from must be greater than to when using a negative step, otherwise R returns a warning.
# Countdown from 100 to 0
countdown_100 <- seq(100, 0, by = -10)
cat('Countdown:', countdown_100, '
')
# Temperature drop simulation
start_temp <- 30.0
end_temp <- 15.0
hourly_temps <- seq(start_temp, end_temp, by = -1.5)
cat('Hourly cooling:', hourly_temps, '
')Floating Point Sequences
Be careful with floating-point steps: tiny rounding errors can cause the last value to be unexpectedly included or excluded. Using length.out instead of by avoids this issue.
# Floating point step: may include or exclude endpoint
seq_by <- seq(0, 1, by = 0.1)
cat('By 0.1 (', length(seq_by), 'values):', seq_by, '
')
# length.out: always exactly n values
seq_lo <- seq(0, 1, length.out = 11)
cat('length.out=11:', seq_lo, '
')
# Check: are they the same?
cat('Identical?', identical(seq_by, seq_lo), '
')Using seq() for Plot Axes
A common use of seq() is generating values for mathematical functions or axis tick marks. It lets you sample a function over an interval at regular intervals.
# Sample a sine wave
x_vals <- seq(0, 2 * pi, length.out = 13)
y_vals <- round(sin(x_vals), 3)
cat('x values (radians):', round(x_vals, 2), '
')
cat('sin(x) values: ', y_vals, '
')
# Find the approximate peak
cat('Peak near x =', round(x_vals[which.max(y_vals)], 3), '
')seq() vs : Comparison
Use : when you want integers with step 1. Use seq() when you need decimal steps, a specific count, or to match another vector's length. They can produce identical results for simple integer ranges.
# These produce the same integer sequence
a <- 1:5
b <- seq(1, 5)
c_seq <- seq(1, 5, by = 1)
d <- seq(1, 5, length.out = 5)
cat('1:5 :', a, '
')
cat('seq(1,5) :', b, '
')
cat('seq(1,5,by=1) :', c_seq, '
')
cat('seq(1,5,lo=5) :', d, '
')
cat('All identical? :', identical(a, d), '
')Practical: Generating Time Points
seq() is ideal for creating time axes in data analysis — for example, generating monthly, quarterly, or yearly intervals for time series work.
# Monthly data points (as numeric month indices)
months_idx <- seq(1, 12, by = 1)
month_names <- month.abb # built-in R constant
cat('Month indices:', months_idx, '
')
cat('Month names :', month_names, '
')
# Quarterly: every 3 months
quarters <- seq(1, 12, by = 3)
cat('Quarter starts:', quarters, '
')
cat('Quarter names :', month_names[quarters], '
')seq() Arguments Summary
Here is a quick reference for seq() arguments:
from— starting value (default 1)to— ending value (default 1)by— step size between valueslength.out— exact number of values to generatealong.with— match length of another vector
Only one of by or length.out should be provided.
# Five different forms of seq()
cat('seq(5) :', seq(5), '
')
cat('seq(2, 10) :', seq(2, 10), '
')
cat('seq(0, 1, by=0.25) :', seq(0, 1, by = 0.25), '
')
cat('seq(0, 1, length.out=5):', seq(0, 1, length.out = 5), '
')
cat('seq(along.with=1:4) :', seq(along.with = 1:4), '
')Quick Check
How many values does seq(0, 1, length.out = 6) produce?
Recap: seq() for Custom Sequences
Great work! Key takeaways from this lesson:
seq(from, to, by)— create sequence with fixed step sizeseq(from, to, length.out = n)— create exactly n evenly spaced valuesseq(along.with = x)— generate indices matching vector xseq_len(n)— safe version of 1:n (handles n=0)- Prefer
length.outoverbyfor floating-point sequences to avoid rounding issues - Use
seq()when:is insufficient (non-integer steps, fixed count)
# Final demo: all seq() forms
cat('Even 0-10: ', seq(0, 10, by = 2), '
')
cat('5 in [0,1]: ', seq(0, 1, length.out = 5), '
')
cat('Match 3-elem: ', seq(along.with = c('a', 'b', 'c')), '
')
cat('Safe 1:0: ', seq_len(0), '(empty)
')Frequently asked questions
Is the “seq() for Custom Sequences” lesson free?
Yes — the full text of “seq() for Custom Sequences” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.
What will I learn in “seq() for Custom Sequences”?
Control step size, length, and direction with seq(). 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; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “seq() for Custom Sequences” 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
- The Colon Operator for Integer Ranges
- seq() for Custom Sequences
- rep() for Repeating Values
- Named Vectors and Named Sequences