R seq() Function - Generating Sequences
The R seq() function is used to generate regular numeric sequences.
seq() is more flexible than the colon operator :, allowing you to specify a step size or sequence length.
The syntax of the seq() function is as follows:
seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)), length.out = NULL)
Parameter Description:
-
from The starting value.
-
to The ending value.
-
by The step size (increment).
-
length.out The desired length of the sequence.
Example
Basic usage: specify a step size
(
"Step size of 2:"
)
(
seq
(
from
=
1
, to
=
10
,
by
=
2
)
)
(
"Step size of 0.5:"
)
(
seq
(
from
=
0
, to
=
3
,
by
=
0.5
)
)
Specify the length
(
"Divided into 5 points:"
)
(
seq
(
from
=
1
, to
=
10
, length.
out
=
5
)
)
Reverse-order sequence
(
"Reversed:"
)
(
seq
(
from
=
10
, to
=
1
,
by
=
2
)
)
The output of the code above is:
[1] "步长为 2:"
[1] 1 3 5 7 9
[1] "步长为 0.5:"
[1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0
[1] "等分为 5 个点:"
[1] 1.00 3.25 5.50 7.75 10.00
[1] "逆序:"
[1] 10 8 6 4 2
seq() is very commonly used in plotting and data generation, for example to create x-axis coordinate points:
Example
Generate x coordinates for plotting
x
<-
seq
(
pi
,
pi
, length.
out
=
100
)
Compute the corresponding y = sin(x)
y
<-
sin
(
x
)
Print the first few points
(
"First 5 coordinate points:"
)
for
(
i
in
1
:
5
)
{
cat
(
sprintf
(
"(%.2f, %.2f)\n"
, x
[
i
]
, y
[
i
]
)
)
}
The output of the code above is:
[1] "前 5 个坐标点:"
(-3.14, -0.00)
(-3.08, -0.06)
(-3.01, -0.13)
(-2.95, -0.19)
(-2.89, -0.25)
R Language Examples