Skip to main content
v2026.11,986 entries · CC-BY 4.0

Sequence function in R: seq() and sequence()

Generate numeric grids and grouped integer runs in R, with worked examples for choosing arguments, checking output and handling empty inputs.

Written and maintained by CASRAI Editorial Board

Published

On this page

The sequence function in R usually means seq(), which generates regularly spaced numbers. R also has a separate sequence() function that joins several integer sequences. Use seq() for a numeric grid, sequence() for grouped runs, and seq_along() for positions within an existing vector.

What sequence functions in R are used for in research

Sequence generation supplies coordinates and indices for analysis scripts. An analyst might need a grid of proposed predictor values, numbered observations within groups, or regular calendar dates. These are constructed values: generating a planned grid does not establish that observations were collected at those points.

The distinction between the two function names matters. In seq(from = 2, to = 10, by = 2), the endpoint and increment determine one run: 2, 4, 6, 8, 10. In sequence(c(2, 4)), the two inputs are lengths, producing a two-element run followed by a four-element run. With the defaults, the result is 1, 2, 1, 2, 3, 4.

For a research script, write down whether the requirement concerns endpoints, spacing, output count, or separate groups before choosing arguments. These requirements produce different checks. A grid intended to have five values should be checked for five elements; a grid intended to advance in increments of two should be inspected for those increments.

The downloadable data table below compares these choices across the official references. It separates generating values, generating positions, repeating labels and generating dates, so a script’s purpose can be matched to the relevant interface.

How to install or access sequence functions in R

These functions belong to R’s base package. With R available, the examples do not require installing an additional sequence package. Obtain R through the Comprehensive R Archive Network. RStudio is an optional interface; Posit’s Get Started guide distinguishes installing R from installing RStudio.

In RStudio, enter a short expression in the Console pane. Put the complete example in an R script in the Source pane when you want to save it. Posit documents the Run command and the Ctrl+Enter shortcut, or Cmd+Enter on macOS, for executing a line. Its project workflow keeps the script and analysis files together through File → New Project.

Open the installed help with help("seq") or help("sequence"). For calendar sequences, use help("seq.Date"). Check the help belonging to the R installation running your script when comparing examples from different documentation versions. The examples here use the signatures in the linked R Core references and do not require development-only arguments.

How to generate sequences in R step by step

  1. Generate one run with a specified increment. This illustrative example represents five planned values, beginning at two and advancing by two. Name the arguments so their roles remain clear when the expression is moved into a longer script.

    seq(from = 2, to = 10, by = 2)
    # Expected values: 2 4 6 8 10

    The first value is two; four further increments reach ten. There are five elements, because the starting value is itself an element. Counting only the increments would give four and understate the output length.

  2. Specify a count when the number of grid points is fixed. Suppose an illustrative plotting grid needs six values spanning zero through ten. Here the number of points is the requirement, so use length.out.

    seq(from = 0, to = 10, length.out = 6)
    # Expected values: 0 2 4 6 8 10

    Six points create five intervals. The interval width is therefore ten divided by five, or two. For the same endpoints, eleven points would create ten intervals. This arithmetic is a useful check when a figure specification refers to points but a script author has been thinking in intervals.

  3. Generate separate runs from group lengths. For an illustrative composite dataset, imagine three groups with three, two and four records. The values are constructed to demonstrate indexing; they are not observations from a study.

    sequence(nvec = c(3, 2, 4))
    # Expected values: 1 2 3 1 2 1 2 3 4

    Read the result as three pieces: 1, 2, 3 for the first group; 1, 2 for the second; and 1, 2, 3, 4 for the third. The lengths add to nine. A single call has concatenated the runs into one vector, rather than retaining three separate containers.

  4. Change each group’s start and increment. Keep the same lengths, but give the three groups different starting coordinates and step sizes.

    sequence(nvec = c(3, 2, 4),
             from = c(0, 10, 20),
             by = c(2, 5, -2))
    # Expected values: 0 2 4 10 15 20 18 16 14

    The first block has three values starting at zero with a step of two. The second has two values starting at ten with a step of five. The third has four values starting at twenty and decreasing by two. Expand the calculation block by block when reviewing a script: a correct total of nine alone would not detect an incorrect starting coordinate.

  5. Create matching group labels. The times argument of rep() can repeat each label according to its group’s record count.

    rep(c("A", "B", "C"), times = c(3, 2, 4))
    # Expected labels: A A A B B C C C C

    Align these nine labels with the nine generated positions. Records one through three belong to A, records four and five to B, and the last four to C. This is an example of constructing labels from known group counts; it does not infer membership from measurements. If the group membership already exists in imported data, preserve that information rather than replacing it with an assumed order.

  6. Check the resulting length explicitly. R’s length() reports the element count of a vector.

    length(sequence(nvec = c(3, 2, 4)))
    # Expected result: 9

    Use the same check for the label vector and inspect the transition between groups. If downstream code needs one object per group, a list in R is a different structure from the single vector returned here.

How to read the output

For seq(), inspect the values, endpoints and element count as separate properties. For sequence(), also inspect the boundaries implied by nvec. Printed spaces separate values; they do not preserve a record of which generated block produced each value. The repeated ones in the grouped example are deliberate restarts.

Console output can wrap onto several lines. R’s printing settings control width and displayed precision, so a different line break or number of printed decimal places does not, by itself, show that a sequence changed. Keep the expression that generated the vector alongside the result. Do not copy a rounded console display back into an analysis and assume it preserves every stored digit.

Positions versus observed values

Given the illustrative vector c(12, 18, 27), seq_along(c(12, 18, 27)) produces positions 1, 2, 3. It does not produce 12, 18, 27 or interpolate between those measurements. When applying a calculation by position, use the index to extract the corresponding observation. The guide to for loops in R explains that next step.

Regular sequences of dates

For calendar dates, provide a Date object so R uses the date method. In this illustrative schedule, weekly spacing is explicit:

seq(from = as.Date("2026-01-05"),
    by = "week", length.out = 3)
# Expected dates: 2026-01-05 2026-01-12 2026-01-19

The returned vector retains the Date class. The official date method accepts day, week, month, quarter and year increments; a numeric increment means days. Prefer the named calendar unit when that is the actual scheduling rule, rather than treating every month as an assumed fixed number of days.

Troubleshooting sequence functions in R

A decreasing sequence has an increasing step

For numeric seq(), the increment must point toward the endpoint. If the start is ten and the endpoint is two, a positive step points away from the target. R documents this disagreement as an error. Use seq(from = 10, to = 2, by = -2) for the illustrative values 10, 8, 6, 4, 2.

The final value falls short of the endpoint

A fixed increment need not land on the endpoint. For example, seq(from = 2, to = 11, by = 4) gives 2, 6, 10. The next value would be fourteen, beyond the endpoint. If including both endpoints with a specified number of points is the requirement, use the count-based pattern instead. Choose the requirement first; appending the endpoint manually would introduce a different final interval.

An empty input unexpectedly creates indices

The expression 1:0 contains two values: one and zero. For positions based on an existing vector, use seq_along(); for a known count, use seq_len(). The examples seq_along(numeric(0)) and seq_len(0) return empty integer vectors. This matters when a filtered dataset contains no records and should produce no indices.

Grouped decimal steps behave unexpectedly

The documented default sequence() method coerces its length, start and increment vectors to integers. It is therefore unsuitable for preserving a requested fractional increment. Use the numeric seq() interface for a decimal grid. Keep the grouped integer example and the decimal-grid example separate in the script so their assumptions remain visible.

Labels and generated coordinates no longer align

Check that both expressions use the same group order and counts. A scalar times repeats the whole input label vector, whereas a matching vector of counts repeats individual labels. Replacing the counts with one scalar can therefore produce a different arrangement even when the resulting length happens to match. Inspect actual labels at the boundaries, not just the total.

Free alternatives to sequence functions in R

The alternatives below are interfaces already available within R. They address different construction tasks; changing the function should follow a change in the required output. Each choice follows the linked R Core documentation.

Required output Alternative Example and distinction
Consecutive numbers with unit spacing The colon operator 4:7 gives 4, 5, 6, 7. Use seq() when another increment or a fixed point count is required.
Positions for each element of a vector seq_along() Uses the input’s length, including the empty-vector case.
Positions from one through a supplied count seq_len() seq_len(3) gives 1, 2, 3; a zero count produces no positions.
Repeated labels or values rep() Repeats supplied values rather than calculating a progression between endpoints.

Random selection is another task again. A regular progression creates values according to its spacing rule; it is not a sampling procedure. For drawing observations or indices, see sampling with sample() in R. Keep the construction rule in the saved script so another analyst can reproduce the intended coordinates and labels.

Sources

Data: R sequence specification and validation crosswalk

Original crosswalk compiled from R Core function references, comparing controlling inputs and validation properties for numeric grids, grouped runs, dates, repeated labels and vector positions. Describes documented interfaces; it contains no observed research measurements.

R sequence specification and validation crosswalk
ConstructionControlling inputsProperty to validateOfficial reference
Numeric run by incrementseq: from, to, byStep direction agrees with endpoint direction; fixed increments may stop short of to.Sequence Generation
Numeric run by point countseq: from, to, length.outRequested number of equally spaced values spans the supplied endpoints.Sequence Generation
Concatenated integer runssequence: nvec, from, bynvec specifies each run length; from and by are integer-coerced and recycled across runs.Create A Vector of Sequences
Calendar-date runseq with Date input: by, length.outNumeric by means days; named day/week/month/quarter/year units are accepted; result retains Date class.Generate Regular Sequences of Dates
Group labels from countsrep: input labels, vector timesEach label is repeated by its corresponding non-negative count when times matches the input length.Replicate Elements of Vectors and Lists
Positions of existing vectorseq_along: along.withOutput counts positions according to input length; an empty input produces no positions.Sequence Generation

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Sequence function in R: seq() and sequence()

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →