Sequences
Featured in 4 main posts
R offers the possibility to easily create finite arithmetic sequences, i.e. sets of numbers in ascending or descending order, distanced by a stable increment. In R, sequences are essentially numeric vectors. An example of a sequence is [13,10,7,4]. An even more straightforward example is [1,2,3,4,5].
General arithmetic sequences
The main way to create arithmetic sequence vectors in R is the seq function. To create the first example:
seq(from=13,to=4,by=-3)
## [1] 13 10 7 4
It’s equally simple to create the second example:
seq(from=1,to=5,by=1)
## [1] 1 2 3 4 5
When the increment is 1…
It’s even simpler to produce sequences where the increment is 1 (by=1) without using seq at all, by just separating the start and end point with : (colon):
1:5
## [1] 1 2 3 4 5
…and the start point is 1
Lastly, there are convenient functions to produce sequences that increment by 1 and start from 1.
- When the length is known as a number, the
seq_lenfunction:
seq_len(length.out=5)
## [1] 1 2 3 4 5
- When the length must be the same as another vector’s, the
seq_alongfunction:
# Suppose we have a vector L of 5 elements
L <- c("A","B","C","D","E")
seq_along(along.with=L)
## [1] 1 2 3 4 5
What about geometric sequences?
If we need a geometric sequence, such as [2, 4, 8, 16, 32], R does not have an out-of-the-box solution for us. Fear not though - it’s very easy to make such a sequence from an arithmetic one. All we need is a bit of math. After all, it’s true that:
[2, 4, 8, 16, 32] = [21, 22, 23, 24, 25] = 2[1, 2, 3, 4, 5]
To reproduce this with R:
2^(1:5)
## [1] 2 4 8 16 32