The seq() function used to generate sequence of numbers with specified increment or decrement between values.
The following method shows how you can do it with syntax.
Method 1: Use seq() Function
seq(from=x, to=y, by=n, length.out=a)
from: Used to specify the starting point of sequence to: Used to specify the ending point of sequence by: Used to add increment or decrement between values length.out: Used to specify length of sequence
The following examples shows how to use seq() function in R.
Use seq() Function to Create Sequence with Specific Incrementing
Let’s see how we can create sequence from 1 to 15 which incremented by 3:
# Define sequence
x <- seq(from=1,to=15,by=3)
# Show sequence
print(x)
Output:
[1] 1 4 7 10 13
Here in the above code we create sequence of values from 1 to 15 with increment of 3 using seq() function.
Use seq() Function to Create Sequence with Specific Decrementing
Suppose we want to create sequence from 20 to 5 which decremented by 2:
# Define sequence
x <- seq(from=20,to=5,by=-2)
# Show sequence
print(x)
Output:
[1] 20 18 16 14 12 10 8 6
As we can see in output sequence is created from 20 to 5 which decremented by 2.
Use seq() Function to Generate Sequence of Specific Length
We can create sequence with specific length using length.out argument:
# Define sequence
x <- seq(from=1,to=20,by=5)
# Show sequence
print(x)
Output:
[1] 1 6 11 16
In the above code we create sequence from 1 to 20 with length size 4. This sequence pick any random values using specified length from define range.