Extract every Nth element of a vector in R
In this article, we will see how to extract every Nth element from a vector in R Programming Language.
Method 1: Using iteration
An iteration is performed over the vector while declaring a variable, counter initialized with 0. With each iteration, the counter is incremented and as soon as the nth element is accessed, it is printed and the counter is reinitialized to 0. As a result, a sequence of elements at every nth index is obtained. The time complexity required in this approach is O(n), where n is the length of the vector.
Method 2: Using iteration and modulo
An iteration is performed over the vector while declaring a variable, counter initialized with 0. With each iteration, the counter is incremented and its modulo is checked with the nth element specified. If the result of the module operation is 0, then the element is printed. The time complexity required in this approach is O(n), where n is the length of the vector.
Method 3: Using seq() function
The seq() method in R, is used to generate sequences, out of the objects they refer to. The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration. It accesses the element at the index of the given vector based on these constraints, and then appends it to a sequence object.
Syntax: seq (from, to , increment_step)
- from – the starting index of the sequence.
- to – the ending index of the sequence, till where we wish to iterate.
- increment_step – how many elements to skip
A sequence based on the constraints.
 “Original vector:”
 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 “Extracting every 4th element”
 “Resultant elements”
 5 9 13 17