VOOZH about

URL: https://www.geeksforgeeks.org/r-language/extract-every-nth-element-of-a-vector-in-r/

⇱ Extract every Nth element of a vector in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Extract every Nth element of a vector in R

Last Updated : 23 Jul, 2025

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. 

Example

Output

[1] 3

[1] 4

[1] 8

The time complexity is O(n), where n is the size of the vector. 

The auxiliary space is O(1)

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.

Example

Output

[1] "for"

[1] "is"

[1] "unique"

[1] "to"

[1] "and"

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)

Parameters :

  • 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

Returns : 

A sequence based on the constraints.

Example

Output

[1] "Original vector:"

[1]  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[1] "Extracting every 4th element"

[1] "Resultant elements"

[1]  5  9 13 17

Comment

Explore