How to Use seq Function in R (With Examples)


The seq() function in R can be used to generate a sequence of numbers.

This function uses the following basic syntax:

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

where:

  • from: The starting value of the sequence.
  • to: The end value of the sequence.
  • by: The value to increment by. Default is 1.
  • length.out: The desired length of the sequence.
  • along.with: The desired length that matches the length of this data object.

The following examples show how to use this function to generate sequences of numbers in practice.

Example 1: Generate Sequence Starting from One

The following code shows how to generate a sequence of values from 1 to 20:

#define sequence
x <- seq(20)

#view sequence
x

[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

Example 2: Generate Sequence with Specific Start and End Values

The following code shows how to generate a sequence of values from 5 to 15:

#define sequence
x <- seq(from=5, to=15)

#view sequence
x

[1]  5  6  7  8  9 10 11 12 13 14 15

Example 3: Generate Sequence with Custom Incrementing

The following code shows how to generate a sequence of values from 0 to 20, incrementing by 4:

#define sequence
x <- seq(from=0, to=20, by=4)

#view sequence
x

[1]  0  4  8 12 16 20

Example 4: Generate Sequence with Specific Length

The following code shows how to generate a sequence of values from 0 to 20, where the specified length of the sequence is 4:

#define sequence
x <- seq(from=0, to=20, length.out=4)

#view sequence
x

[1]  0.000000  6.666667 13.333333 20.000000

Example 5: Generate Sequence with Length Based on Some Data Object

The following code shows how to generate a sequence of values from 0 to 20, where the specified length of the sequence should match the length of another data object:

#define vector y
y <- c(1, 4, 6, 9)
 
#define sequence x, make sure length matches the length of y
x <- seq(from=0, to=20, along.with=y)

#view sequence
x

[1]  0.000000  6.666667 13.333333 20.000000

Notice that sequence x goes from 0 to 20 and its length (4) matches the length of vector y.

Additional Resources

How to Use the sample() Function in R
How to Use the dist() Function in R
How to Use the table() Function in R

Leave a Reply

Your email address will not be published.