seq() function in R generates a sequence of numbers.
Syntax for seq() function in R:
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
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
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
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.