The seq_len() function in R is used to generate a sequence of integers from 1 to a specified length. For example, seq_len(5) will return 1, 2, 3, 4, 5.
This function is helpful in creating sequences when you need to generate indices or iterate over a sequence of numbers in loops and vectorized operations.
Syntax
seq_len(num)
Parameters
num: It is a specified number.
Return value
It returns integers from 1 up to n. If num is less than or equal to 0, seq_len() returns an empty integer vector.
Example 1: Usage of seq_len()
seq_len(1)
seq_len(2)
seq_len(6)
Output
[1] 1
[1] 1 2
[1] 1 2 3 4 5 6
Example 2: Creating an empty sequence
num <- 0
seq_len(num)
Output
integer(0)
The “integer(0)” is a length zero sequence of integers.
In the past, we used the “colon sequence” notation to create sequences.
But there is a problem using this notation. The colon sequence notation can be dangerous as it does not handle the empty sequence case correctly.
num <- 0
1:num
Output
[1] 1 0
Example 3: Creating an index of a vector
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.
vec <- c(11, 18, 19, 21, 46)
lnt <- length(vec)
seq_len(lnt)
Output
[1] 1 2 3 4 5
You can see that we created a sequence of integers from 1 to lnt, where lnt is the length of the vector vec.
See also
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.