R seq() Function - Generating Sequences

R 语言实例R Language Examples

The R seq() function is used to generate regular numeric sequences.

seq() is more flexible than the colon operator :, as it allows specifying the 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:

  • fromStarting value.

  • toEnding value.

  • byStep size (increment).

  • length.outThe desired length of the sequence.

Example

# Basic usage: specify the step size
print("Step size of 2:")
print(seq(from = 1, to = 10, by = 2))

print("Step size of 0.5:")
print(seq(from = 0, to = 3, by = 0.5))

# Specify the length
print("Divided into 5 points:")
print(seq(from = 1, to = 10, length.out = 5))

# Reverse sequence
print("Reverse order:")
print(seq(from = 10, to = 1, by = -2))

Executing the above code produces the following output:

[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, creating x-axis coordinates:

Example

# Generate x coordinates for plotting
x <- seq(-pi, pi, length.out = 100)

# Calculate the corresponding y = sin(x)
y <- sin(x)

# Print the first few points
print("First 5 coordinate points:")
for (i in 1:5) {
  cat(sprintf("(%.2f, %.2f)\n", x[i], y[i]))
}

Executing the above code produces the following output:

[1] "前 5 个坐标点:"
(-3.14, -0.00)
(-3.08, -0.06)
(-3.01, -0.13)
(-2.95, -0.19)
(-2.89, -0.25)

R 语言实例R Language Examples

Other Extensions