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
-
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 10The 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.
-
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 10Six 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.
-
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 4Read 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.
-
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 14The 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.
-
Create matching group labels. The
timesargument ofrep()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 CAlign 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.
-
Check the resulting length explicitly. R’s
length()reports the element count of a vector.length(sequence(nvec = c(3, 2, 4))) # Expected result: 9Use 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
- R Core: Sequence Generation, checked 2026-11-17.
- R Core: Create A Vector of Sequences, checked 2026-11-17.
- R Core: Replicate Elements of Vectors and Lists, checked 2026-11-17.
- R Core: Generate Regular Sequences of Dates, checked 2026-11-17.
- R Core: Length of an Object, checked 2026-11-17.
- R Core: An Introduction to R, checked 2026-11-17.
- R Core: Default Printing, checked 2026-11-17.
- Posit: Get Started — RStudio User Guide, checked 2026-11-17.
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.
| Construction | Controlling inputs | Property to validate | Official reference |
|---|---|---|---|
| Numeric run by increment | seq: from, to, by | Step direction agrees with endpoint direction; fixed increments may stop short of to. | Sequence Generation |
| Numeric run by point count | seq: from, to, length.out | Requested number of equally spaced values spans the supplied endpoints. | Sequence Generation |
| Concatenated integer runs | sequence: nvec, from, by | nvec specifies each run length; from and by are integer-coerced and recycled across runs. | Create A Vector of Sequences |
| Calendar-date run | seq with Date input: by, length.out | Numeric by means days; named day/week/month/quarter/year units are accepted; result retains Date class. | Generate Regular Sequences of Dates |
| Group labels from counts | rep: input labels, vector times | Each label is repeated by its corresponding non-negative count when times matches the input length. | Replicate Elements of Vectors and Lists |
| Positions of existing vector | seq_along: along.with | Output counts positions according to input length; an empty input produces no positions. | Sequence Generation |
Sources
- R: Sequence Generation (accessed 2026-11-17)
- R: Create A Vector of Sequences (accessed 2026-11-17)
- R: Generate Regular Sequences of Dates (accessed 2026-11-17)
- R: Replicate Elements of Vectors and Lists (accessed 2026-11-17)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







