seq_len in R: How to Create a Sequence from 1 to N

In the past, we used the colon sequence” notation to create sequences.

for (k in 1:5) {
 print(paste(k))
}

Output

[1] "1"
[1] "2"
[1] "3"
[1] "4"
[1] "5"

But there is a problem using this notation. The colon sequence notation can be dangerous as it does not correctly handle the empty sequence case.

num <- 0

1:num

Output

[1] 1  0

From the output, you can see that it built a reverse sequence instead of creating an empty sequence. This points to the backward sequence trap: writing code of the form “1:length(x)” is oftentimes wrong.

To solve this problem, use a function in R called seq_len(). Let’s see how it can create sequences as we want and handle the empty sequence properly.

seq_len in R

The seq_len() in R is a built-in function that generates a sequence from 1 to the specified number. The seq_len() method creates a sequence that starts at 1 and with steps of 1 finishes at the number value.

To create any number sequence in R, use the seq_len() function.

Syntax

seq_len(num)

Arguments

num: It is a specified number.

Example

Let’s create some sequences.

seq_len(1)
seq_len(2)
seq_len(6)

Output

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

Creating an empty sequence in R

To create an empty sequence in R, use the seq_len() method.

num <- 0

seq_len(num)

Output

integer(0)

The “integer(0)” is a length zero sequence of integers.

Creating an index of a Vector using seq_len()

To create an index of a Vector, you can use the seq_len() function. Firstly, create a Vector using the c() function and then find its length using the length() function and then pass the output to the seq_len() function.

rv <- c(11, 18, 19, 21, 46)
lnt <- length(rv)
seq_len(lnt)

Output

[1] 1  2  3  4  5

And we get the indices of each element of the Vector.

Difference between seq_len() and seq_along()

The seq_along(n) function accepts a vector for n, and it creates a sequence up to the count of elements in the vector.

The seq_len(n) method accepts numeric for n, it creates a sequence up to the number n.

The seq_along(n) function is the same as seq_len(length(n)).

The seq_len(n) function is the same as seq_len(n[1]).

Conclusion

There are many ways to create a sequence in R, but the seq_len() method is mostly used because it only takes one argument, and it is effortless to understand when the code is dense.

See also

seq() in r

as.character in r

chartr in r

Leave a Comment