R Language Creating vectors seq()


Example

seq is a more flexible function than the : operator allowing to specify steps other than 1.

The function creates a sequence from the start (default is 1) to the end including that number.

You can supply only the end (to) parameter

seq(5)
# [1] 1 2 3 4 5

As well as the start

seq(2, 5) # or seq(from=2, to=5)
# [1] 2 3 4 5

And finally the step (by)

seq(2, 5, 0.5) # or seq(from=2, to=5, by=0.5)
# [1] 2.0 2.5 3.0 3.5 4.0 4.5 5.0

seq can optionally infer the (evenly spaced) steps when alternatively the desired length of the output (length.out) is supplied

seq(2,5, length.out = 10)
# [1] 2.0 2.3 2.6 2.9 3.2 3.5 3.8 4.1 4.4 4.7 5.0

If the sequence needs to have the same length as another vector we can use the along.with as a shorthand for length.out = length(x)

x = 1:8
seq(2,5,along.with = x)
# [1] 2.000000 2.428571 2.857143 3.285714 3.714286 4.142857 4.571429 5.000000

There are two useful simplified functions in the seq family: seq_along, seq_len, and seq.int. seq_along and seq_len functions construct the natural (counting) numbers from 1 through N where N is determined by the function argument, the length of a vector or list with seq_along, and the integer argument with seq_len.

seq_along(x)
# [1] 1 2 3 4 5 6 7 8

Note that seq_along returns the indices of an existing object.

# counting numbers 1 through 10
seq_len(10)
[1]  1  2  3  4  5  6  7  8  9 10
# indices of existing vector (or list) with seq_along
letters[1:10]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
seq_along(letters[1:10])
[1]  1  2  3  4  5  6  7  8  9 10

seq.intis the same as seq maintained for ancient compatibility.

There is also an old function sequencethat creates a vector of sequences from a non negative argument.

sequence(4)
# [1] 1 2 3 4
sequence(c(3, 2))
# [1] 1 2 3 1 2
sequence(c(3, 2, 5))
# [1] 1 2 3 1 2 1 2 3 4 5