Generate sequence with seq() function in R

seq() function in R generates a sequence of numbers.

Syntax for seq() function in R:

seq(from, to, by, length.out)

 

from beginning of the sequence
to end of the sequence
by increment by (default is 1)
length.out length of the sequence

Example of simple Seq() function in R:

Lets see a simple example of seq() function in R

# sequence from 5 to 10 with R seq function

seq(5,10)

Above seq() function in R, takes up 2 parameters “from” and “to” of the sequence, so the resultant output will be

[1]  5  6  7  8  9 10

 

Example of Seq function in R with by keyword: 

# Generate sequence from 0 to 20 incremented by 2 with R seq function

seq(from=0, to=20, by=2)

Above seq() function in R, takes up 3 parameters from, to and by. So it generates the sequence of numbers from 0 to 20 incremented by 2. So the output will be

[1]  0  2  4  6  8  10  12  14  16  18  20

 

Example of Seq function in R with length.out: 

Suppose we don’t know the increment value, but we want some evenly distributed numbers of predefined length, then we can use length.out option

# Generate sequence from 0 to 20 with length.out=5 with R seq function

seq(from=0, to=20, length.out=5)

Above seq() function in R, takes up 3 parameters from, to and length. In this example R will calculate the necessary increment as we predefined the length. So the output will be

[1]  0  5 10 15 20

Seq function in R with Fractional increment:

The increment need not be an integer. R can create sequences with fractional increments too

# Generate sequence from 1 to 3 with length.out=5 with R seq function

seq(from=1.0, to=3.0, length.out=5)

When we execute the above code, the increment will be fractional.

[1] 1.0 1.5 2.0 2.5 3.0

 

previous small seq() function in r                                                                                                          next small seq() function in r

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts