seq

Basics

seq is a function that creates a sequence. Its arguments include:

  • from: the starting point of the sequence

  • to: the end value of the sequence, inclusive

  • by: increment value

  • length.out: desired length of sequence

    • Can be shortened to "length" or "len"

  • along.with: takes an object of length n, creates sequence of length n

    • Can be shortened to "along"

It is standard practice to name the arguments — seq(from=3, to=9, by=3) is easier to read on first glance than seq(3,9,3)

There are 3 primitive (faster but more limited) versions of seq functions that are:

  1. seq.int: limits sequence to contain strictly integers, as seq has ambiguity with doubles or integers depending on input.

  2. seq_along: faster alternative of seq(along.with= )

  3. seq_len: faster alternative of seq(length.out= )


Examples

How do I create a vector with the numbers 1 to 20, inclusive, in 4 different ways?

Click to see solution
# option 1: standard using `seq`
seq(from=1, to=20)
# option 2: faster using `seq.int`
seq.int(from=1, to=20)
# option 3: using `seq_len`
seq_len(20)
# option 4: using `:`, which emulates option 1
1:20
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

How do I create a vector with 5 equally spaced numbers from 1 to 4, inclusive?

Click to see solution
# option 1: `seq`
seq(from=1, to=4, length.out=5)
[1] 1.00 1.75 2.50 3.25 4.00

How would I display every multiple of 3, starting at 60 and ending at 3?

Click to see solution
# option 1: standard `seq`
seq(from=60, to=3, by=-3)
# option 2: quicker `seq.int`
seq.int(from=60, to=3, by=-3)
[1] 60 57 54 51 48 45 42 39 36 33 30 27 24 21 18 15 12  9  6  3
[1] 60 57 54 51 48 45 42 39 36 33 30 27 24 21 18 15 12  9  6  3

The sign is important here — if you don’t include "-" in front of 3, you will receive a wrong sign in 'by' argument error. R assumes you don’t want to receive a sequence obtained with integer overflow.