R seq Function


seq() function generates a sequence of numbers.

seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)),
length.out = NULL, along.with = NULL, ...)


• from, to: begin and end number of the sequence
• by: step, increment (Default is 1)
• length.out: length of the sequence
• along.with: take the length from the length of this argument

Generate a sequence from -6 to 7:

> x <- seq(-6,7)
> x

[1] -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7


The generated sequence is a vector:

> is.vector(x)

[1] TRUE


From -6 till 7, step=2:

> x <- seq(-6,7,by=2)
> x

[1] -6 -4 -2 0 2 4 6


Let's try smaller step:

> x <- seq(-2,2,by=0.3)
> x

[1] -2.0 -1.7 -1.4 -1.1 -0.8 -0.5 -0.2 0.1 0.4
0.7 1.0 1.3 1.6 1.9


Suppose we do not know the step, but we want 10 evenly distributed numbers from -2 to 2:

> seq(-2,2,length.out=10)

[1] -2.0000000 -1.5555556 -1.1111111 -0.6666667 -0.2222222 0.2222222
[7] 0.6666667 1.1111111 1.5555556 2.0000000

If we do not know the step, as well as how many numbers we want, we can use along.with argument to provide an example vector, so length of the result vector will be the same as the example vector.

> x <- c(1,3,"f",5,3)
> seq(1,10,along.with=x)
[1]  1.00  3.25  5.50  7.75 10.00

seq_along(x) is similar to seq(..., along.with=x), except the former takes only an example vector as argument, and returns an integer vector, plus much quicker.

> seq_along(x)
[1] 1 2 3 4 5
> seq_along(10)
[1] 1




Generate a sequence from 1 to 10, simple version:

> x <- seq(10)
> x

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

Generate a sequence from 1 to 10, quick version:

> x <- seq_len(10)
> x

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

seq.int() generates an integer only sequence in a range:

> seq.int(-3,6)

[1] -3 -2 -1  0  1  2  3  4  5  6

endmemo.com © 2024  | Terms of Use | Privacy | Home