How to Use the seq() Function in R

The seq() function in R is “used to generate a regular sequence of numbers”.

Syntax

seq(from, to, by, length.out=NULL, along.with=NULL)

Parameters

  1. from: It represents where the sequence should begin.
  2. to: It represents where the sequence should end.
  3. by: It represents the step size or interval of the sequence.
  4. length.out: The desired length of the sequence.
  5. along.with: The desired length that matches the length of this data object.

Example 1: Generate a Sequence Starting from One

If you pass a single argument, it is considered an ending point, and the starting point is assumed as 1. So your sequence will be from 1 to the ending point.

s <- seq(5)
print(s)

Output

[1] 1 2 3 4 5

In this example, we passed 5 as an ending point. So the sequence is from 1 to 5.

Example 2: Generating a sequence in R

s <- seq(0, 5)
print(s)

Output

[1] 0 1 2 3 4 5

In this example, we are generating a sequence of o to 5. Here, we have passed the starting point and ending point in the sequence.

Example 3: Generate Sequence with Custom Incrementing

vec <- seq(from = 0, to = 20, by = 4)

vec

Output

[1] 0 4 8 12 16 20

Example 4: Generate a Sequence with a Specific Length

data <- seq(from = 0, to = 20, length.out = 4)

# view sequence
data

Output

[1] 0.000000 6.666667 13.333333 20.000000

Example 5: Seq() function with argument “by”

The “by” parameter is an integer that indicates the increment of the sequence.

s <- seq(0, 10, by = 2)
print(s)

Output

[1] 0 2 4 6 8 10

In this example, we are passing by = 2. That means it gives us alternate values. If we have started with 1, it will give us 3, 5, 7, and 9. It stays below the ending value of the sequence. The by value is a kind of step value.

Example 6: Seq() function with argument “length.out”

The “length.out” parameter is the desired length of the sequence.

s <- seq(1, 10, length.out = 11)
print(s)

Output

[1] 1.0 1.9 2.8 3.7 4.6 5.5 6.4 7.3 8.2 9.1 10.0

Here, the length of the sequence is 11. That means it divides the sequence into 11 elements, and there are exactly 11 elements in the 1 to 10 sequence.

Example 7: Seq() function with argument “along”

for (x in list(NULL, letters[1:6], list(1, pi)))
    cat("x=", deparse(x), "; seq(along = x):", seq(along = x), "\n")

Output

x= NULL ; seq(along = x):
x= c("a", "b", "c", "d", "e", "f") ; seq(along = x): 1 2 3 4 5 6
x= list(1, 3.14159265358979) ; seq(along = x): 1 2

That’s it.

2 thoughts on “How to Use the seq() Function in R”

  1. I simply want to mention I am very new to blogging and site-building and really liked this web blog. Very likely I’m likely to bookmark your blog . You actually come with good writings. Appreciate it for sharing with us your blog site.

    Reply

Leave a Comment