Generating Regular Sequences of Numbers

For regularly spaced sequences, often involving integers, it is simplest to use the colon operator. This can produce ascending or descending sequences:

10:18

[1]  10  11  12  13  14  15  16  17  18

18:10

[1]  18  17  16  15  14  13  12  11  10

-0.5:8.5

[1]  -0.5  0.5  1.5  2.5  3.5  4.5  5.5  6.5  7.5  8.5

When the interval is not 1.0 you need to use the seq function. In general, the three arguments to seq are: initial value, final value, and increment (or decrement for a declining sequence). Here we want to go from 0 up to 1.5 in steps of 0.2:

seq(0,1.5,0.2)

[1]  0.0  0.2  0.4  0.6  0.8  1.0  1.2  1.4

Note that seq stops before it gets to the second argument (1.5) if the increment does not match exactly (our sequence stops at 1.4). If you want to seq downwards, the third argument needs to be negative

seq(1.5,0,-0.2)

[1]  1.5  1.3  1.1  0.9  0.7  0.5  0.3  0.1

Again, zero did not match the decrement, so was excluded and the sequence stopped at 0.1. Non-integer increments are particularly useful for generating x values for plotting smooth curves. A curve will look reasonably smooth if it is drawn with 100 straight line segments, so to generate 100 values of x between min(x) and max(x) you could write

x.values<-seq(min(x),max(x),(max(x)-min(x))/100)

If you want to create a sequence of the same length as an existing vector, then use along like this. Suppose that our existing vector, x, contains 18 random numbers from a normal distribution with a mean of 10.0 and a standard deviation ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.