Extract every Nth element of a vector in R
Last Updated :
03 May, 2023
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
R
vec <- c (1,2,3,4,5,4,3,7,8,9)
count = 0
for (i in vec){
count= count + 1
if (count == 3){
print (i)
count = 0
}
}
|
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
R
vec <- c ( "geeks" , "for" , "geeks" , "is" , "a" , "unique" ,
"portal" , "to" , "learn" , "and" , "grow" )
n = 2
count = 0
for (i in vec){
count= count + 1
if (count %% n == 0){
print (i)
}
}
|
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
R
vec <- 5:20
print ( "Original vector:" )
print (vec)
print ( "Extracting every 4th element" )
extracted_vec <- vec[ seq (1, length (vec), 4)]
print ( "Resultant elements" )
print (extracted_vec)
|
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
Share your thoughts in the comments
Please Login to comment...