seq() function to create sequences

seq() function in R is one of the base R functions that is useful in creating sequences. In this tutorial, we will see multiple examples of creating sequence of numbers using seq() function.

FIrst let us start with the simplest example of using seq() function. If you give a number as argument to seq() function, it will gives sequence of number starting from 1 to the input number. For example, if we use seq(5), we get

seq(5)

## [1] 1 2 3 4 5

The basic usage of seq() function is to provide starting point, ending point and by argument that specifies step size.

seq(from = ., to = , by ),

For example, if we use seq(1,5), it will assume the step size to be and give use the sequence of numbers from 1 to 5.

seq(from=1, to=5)

## [1] 1 2 3 4 5

Sequence of numbers between a range with seq() function

Similarly if we give a different starting from number, our sequence will start from that number. For example here we generate sequence of numbers from 10 to 20 by using seq()

seq(10,20)
##  [1] 10 11 12 13 14 15 16 17 18 19 20

Sequence of odd/even numbers between a range with seq() function

With “by” option, we can generate even and odd numbers in a given range. For example to create a odd number of sequences between 1 and 10, we will use

seq(1,10,by=2)

## [1] 1 3 5 7 9

Similarly, to generate a sequence of even numbers we will use seq() function as follows.

seq(2,10,by=2)

## [1]  2  4  6  8 10
Exit mobile version