# How to Create Sequence of Numbers in R?

## Problems –

You want to create a sequence of numbers in R.

## Solution –

Use the colon operator (n:m) to create a vector containing the sequence n, n+1, n+2, …..,m.

> 0:10
[1]  0  1  2  3  4  5  6  7  8  9 10

You can also go in reverse direction.

> 10:0
[1] 10  9  8  7  6  5  4  3  2  1  0

You can also use the colon operator directly with the pipe to pass data to another function.

> 0:10 %>% mean()
[1] 5

The colon operator increment by 1 only. If you want to increment the numbers by certain value you can use the seq function.

> seq(from=0, to=20)
[1]  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
> seq(from=0, to=20, by=2)
[1]  0  2  4  6  8 10 12 14 16 18 20

You can also specify the length of the sequence and R will calculate the necessary increment.

> seq(from=0, to=20, length.out=5)
[1]  0  5 10 15 20

If you want a sequence that has repeated values then you can use the rep function.

> rep(5, times=5)
[1] 5 5 5 5 5

Rating: 1 out of 5.

Posted in RTagged